编程语言
首页 > 编程语言> > php – 使用列标题将CSV处理为数组

php – 使用列标题将CSV处理为数组

作者:互联网

我有一个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);

标签:php,arrays,csv,heading
来源: https://codeday.me/bug/20190919/1811945.html