将 CSV 处理为带有键列标题的数组 [英] Process CSV Into Array With Column Headings For Key

查看:28
本文介绍了将 CSV 处理为带有键列标题的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a CSV with the first row containing the field names. Example data is...

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

我需要将数据格式化为键值对数组,其中键名是列标题.我想第 1 行会是这样的:

I need my data formatted in an array of key-value pairs where the key name is the column heading. I guess it would something like this for row 1:

$array = [
    "Make" => "Chevy",
    "Model" => "1500",
    "Note" => "loaded"
];

...第 2 行...

...row 2...

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

...和第 3 行...

...and row 3...

$array = [
    "Make" => "Chevy",
    "Model" => "",
    "Note" => "loaded"
];

除了静态之外,我不知道如何做到这一点 - 问题是具有关联数据的列可能会从一个文件更改为下一个文件...重新排列、删除或添加的列.

I'm not sure how to do this other than statically - problem is the columns with their associated data could change from one file to the next... columns rearranged, dropped, or added.

非常感谢您的想法.

推荐答案

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

print_r($all_rows);

这篇关于将 CSV 处理为带有键列标题的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆