我正在使用我正在转换为数组的CSV文件。但是,我希望我的数组键是第一行的值。我正在寻找一种简单的方法来完成这项工作。
$newArray = [];
$handle = fopen($file, "r");
$firstRow = fgetcsv($handle, 5000, ",");
while (false !== ($row = fgetcsv($handle, 5000, ','))) {
$newArray[] = $row;
}
现在,$row
将具有数组通常的数字数组键。但是,我希望$firstRow
替换这些密钥。有人可以帮助我吗?
根据要求,提供一些示例数据。
"name","age","active","date_added"
"John Doe","24","yes","2018-01-02"
"Jane Doe","41","yes","2018-01-03"
"Joe Doe","28","yes","2018-01-04"
"Janett Doe","30","no","2018-01-05"
目前,var_dump($row)
将输出:
array(4) {
[0]=> "John Doe"
[1]=> "24"
[2]=> "yes"
[3]=> "2018-01-02"
}
预期结果:
array(4) {
['name']=> "John Doe"
['age']=> "24"
['active']=> "yes"
['date_added']=> "2018-01-02"
}
答案 0 :(得分:2)
只需使用 array_combine()
功能:
...
$newArray[] = array_combine($firstRow, $row);
...