PHP数组生成器
我在excel文件中有一些值,我希望所有这些值都是数组元素记住文件中还有其他数据。 我知道一种方法是一个接一个地复制它们,然后放入数组初始化状态 只是整个列表的一部分的示例列表PHP数组生成器,php,arrays,Php,Arrays,我在excel文件中有一些值,我希望所有这些值都是数组元素记住文件中还有其他数据。 我知道一种方法是一个接一个地复制它们,然后放入数组初始化状态 只是整个列表的一部分的示例列表 Bay Area Greater Boston Greater Chicago Greater Dallas-Ft. Worth Greater D.C. Las Vegas Greater Houston Greater LA Greater New York Greater San Diego Seattle So
Bay Area
Greater Boston
Greater Chicago
Greater Dallas-Ft. Worth
Greater D.C.
Las Vegas
Greater Houston
Greater LA
Greater New York
Greater San Diego
Seattle
South Florida
当没有太多类似的项时,很容易用值初始化数组
$array= array('Bay Area '=>'Bay Area ','Greater Boston'=>'Greater Boston',....)
// and so on
但我有70-80项,像上面这样初始化数组是一项非常繁琐的任务
那么,伙计们,有没有其他方法或捷径来分配数组和值列表
是否有自动阵列生成器工具?此工具:
$string_var = "
Bay Area
Greater Boston
Greater Chicago
Greater Dallas-Ft. Worth
";
$array_var = explode("\n", $string_var);
$string_var=”
湾区
大波士顿
大芝加哥
大达拉斯-沃思英尺
";
$array\u var=explode(“\n”,$string\u var);
对于在PHP中加载CSV文件的更复杂的情况,可以使用或甚至用于XLS文件
编辑(问题编辑后)
(删除了我糟糕的解决方案,因为ohmusama的file()+array_combine()显然更好)获取记事本++,在那里打开excel文件,然后进行简单搜索并用regex替换。类似于搜索“(.*)\n”并替换为“(\1)”(“不包括quoutes),这将为您提供一个很长的列表: “湾区”、“大波士顿”、“大芝加哥”
就php执行时间而言,这将是创建数组的最快方法。我认为它看起来更好:
$a[] = "Bay Area";
$a[] = "Greater Boston";
$a[] = "Greater Chicago";
要创建这样的文本文件,请使用Excel(我没有Excel,但看起来有点像):
然后只导出该列。如果您将它们复制到一个文件中,每个文件都有自己的行,那么您可以像这样用php读取该文件
$myArray = file('myTextFile');
//sets the keys to the array equal to the values
$myArray = array_combine($myArray, $myArray);
您可以将数据从excel导出到CSV,然后将文件读入php,如下所示:
$myArray = array();
if (($file = fopen("myTextFile", "r")) !== FALSE) {
while (($data = fgetcsv($file)) !== FALSE) {
foreach($data as $value) {
$myArray[$value] = $value;
}
}
fclose($handle);
}
对不起,忘了提一下,我需要
key=>value
pair-question-update更新新版本的问题。
$myArray = file('myTextFile');
//sets the keys to the array equal to the values
$myArray = array_combine($myArray, $myArray);
$myArray = array();
if (($file = fopen("myTextFile", "r")) !== FALSE) {
while (($data = fgetcsv($file)) !== FALSE) {
foreach($data as $value) {
$myArray[$value] = $value;
}
}
fclose($handle);
}