PHP - 在数组中使用 include() 函数

发布于 2024-12-12 00:34:16 字数 228 浏览 0 评论 0原文

如何在数组中使用 include() 函数?

例如,我有一个列出了一堆县的数组,我没有将所有县输入到一个数组中,而是创建了一个以逗号分隔的县的 .txt 文件。从逻辑上讲,我认为它应该这样工作:

array (include ("counties.txt"));

但它在数组函数之外生成列表。

是否有在数组中使用 include() 函数的不同方法?

How would I use the include() function within an array?

For example, I have an array which lists a bunch of counties, instead of inputting all of the counties into an array, I created a .txt file of comma delimited counties. Logically, I think it's supposed to work as such:

array (include ("counties.txt"));

But it produces the list outside of the array's function.

is there a different method of using the include() function within an array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寂寞笑我太脆弱 2024-12-19 00:34:17

尝试file_get_contents()

$temp_string = file_get_contents('counties.txt');
$temp_array = array($temp_string);

Try file_get_contents()

$temp_string = file_get_contents('counties.txt');
$temp_array = array($temp_string);
月下客 2024-12-19 00:34:17

我会尝试 readfile(),在新行上分隔每个县。 readfile() 函数将文件的每一行放入索引数组中。

$array = readfile('counties.txt');

I would try readfile(), separating each county on a new line. The readfile() function places each line of the file into an indexed array.

$array = readfile('counties.txt');
七颜 2024-12-19 00:34:16

一种方法是让 counties.txt 文件具有以下格式:

<?php
return array(
    'country1',
    'country2',
    // etc.
);

然后,只需将其包含在数组中,如下所示:

<?php
$arr = include('counties.txt');

另一种方法是解析 counties.txt,如下所示

<?php
$list = file_get_contents('counties.txt');

// Normalize the linebreaks first
$list = str_replace(array("\r\n", "\r"), "\n", $list);

// Put each line into its own element within the array
$arr = explode("\n", $list);

:方式有效并且会产生相同的结果。

One way is for your counties.txt file to have the following format:

<?php
return array(
    'country1',
    'country2',
    // etc.
);

Then, just include it in your array like:

<?php
$arr = include('counties.txt');

Another method is to parse counties.txt like:

<?php
$list = file_get_contents('counties.txt');

// Normalize the linebreaks first
$list = str_replace(array("\r\n", "\r"), "\n", $list);

// Put each line into its own element within the array
$arr = explode("\n", $list);

Either way works and will produce the same result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文