[英]How to convert a text list into a PHP associative array with key=value?
I have a list in a text file: 我在文本文件中有一个列表:
Alabama
Alaska
Alberta
...
and I would like to have a PHP array like that : 我想有一个像这样的PHP数组:
array('Alabama' => 'Alabama', 'Alaska' => 'Alaska', ...)
How could I have this array ? 我怎么能有这个阵列? (I am a beginner in PHP and in computing in general). (我是PHP和计算机的初学者)。 Thanks a lot 非常感谢
You can use file()
to read the entire file to an array, and use array_combine()
to assign the array keys. 您可以使用file()
将整个文件读取到数组,并使用array_combine()
来分配数组键。
$arr = file('file.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$arr = array_combine($arr, $arr);
// read the file as an array of lines
$lines = file('./myFile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// fill the array
$arr = array();
foreach($lines as $line) {
$arr[$line] = $line;
}
You could actually read a file into an array. 您实际上可以将文件读入数组。
$states=require('path/to/states.php');
then in the states.php file 然后在states.php文件中
return array(
'Alabama' => 'Alabama',
'Alaska' => 'Alaska'
// and so on.
);
You would have to format your list, but that should be pretty easy using a text editor with regex. 您必须格式化列表,但使用带有正则表达式的文本编辑器应该非常简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.