我想动态加载一个CSV文件到php中并将其存储在数组中。我无法让数组名变成我想要的形式。第一个数组应该正常编号,第二个数组应该包含CSV文件的头。
这是我目前解决的问题:
static function parseCSV($path){
$fp = file($path);
$array = array();
for ($i = 0; $i < count($fp); $i++) {
$e = explode("," , $fp[$i+1]);
foreach($e as $data){
$array[$e[0]][] = $data;
}
}
print_r($array);
}
这是输出:
Array
(
[Louis] => Array
(
[0] => Louis
[1] => 000
[2] => 01.01.2001
[3] => Canada
)
[Hannah] => Array
(
[0] => Hannah
[1] => 001
[2] => 02.02.2002
[3] => Germany
)
)
我想要的输出:
Array
(
[1] => Array
(
[name] => Louis
[id] => 000
[birthday] => 01.01.2001
[country] => Canada
)
[2] => Array
(
[name] => Hannah
[id] => 001
[birthday] => 02.02.2002
[country] => Germany
)
)
您可以使用特定的数组索引创建一个新的行数据数组:
static function parseCSV($path){
$headers = ['name', 'id', 'birthday', 'country'];
$fp = file($path);
$array = array();
for ($i = 0; $i < count($fp); $i++) {
$rows = explode("," , $fp[$i+1]);
foreach($rows as $row) {
$associativeArray = array();
foreach($row as $index=>$value) {
$associativeArray[$headers[$index]] = $value;
}
array_push($array, $associativeArray);
}
}
print_r($array);
}