我有一个CSV,第一行包含字段名称。示例数据是...

"Make","Model","Note"
"Chevy","1500","loaded"
"Chevy","2500",""
"Chevy","","loaded"

我需要将数据格式化为键-值对数组,其中键名是列标题。我想第1行会是这样的:
$array = [
    "Make" => "Chevy",
    "Model" => "1500",
    "Note" => "loaded"
];

第2行
$array = [
    "Make" => "Chevy",
    "Model" => "1500",
    "Note" => ""
];

...以及第3行...
$array = [
    "Make" => "Chevy",
    "Model" => "",
    "Note" => "loaded"
];

除了静态以外,我不确定如何执行此操作-问题是带有关联数据的列可能从一个文件更改为下一个文件...重新排列,删除或添加了列。

非常感谢您的想法。

最佳答案

$all_rows = array();
$header = fgetcsv($file);
while ($row = fgetcsv($file)) {
  $all_rows[] = array_combine($header, $row);
}
print_r($all_rows);

08-05 15:09