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

Mec*_*ash 0 php arrays function include

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

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

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

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

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

nic*_*jyc 5

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

<?php
return array(
    'country1',
    'country2',
    // etc.
);
Run Code Online (Sandbox Code Playgroud)

然后,只需将其包含在您的数组中,例如:

<?php
$arr = include('counties.txt');
Run Code Online (Sandbox Code Playgroud)

另一种方法是解析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);
Run Code Online (Sandbox Code Playgroud)

无论哪种方式都有效,并且会产生相同的结果。