I'm currently working with a CSV file that I am converting into an array. However, I would like for my array keys to be the values of the first row. I'm looking for an easy way to get this done.
$newArray = [];
$handle = fopen($file, "r");
$firstRow = fgetcsv($handle, 5000, ",");
while (false !== ($row = fgetcsv($handle, 5000, ','))) {
$newArray[] = $row;
}
Now, $row
will have numeric array keys as is usual with arrays. However, I would like $firstRow
to replace those keys. Can someone help me out?
As requested, some example data.
"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"
Currently, var_dump($row)
will output:
array(4) {
[0]=> "John Doe"
[1]=> "24"
[2]=> "yes"
[3]=> "2018-01-02"
}
The expected result:
array(4) {
['name']=> "John Doe"
['age']=> "24"
['active']=> "yes"
['date_added']=> "2018-01-02"
}
Simply with array_combine()
function:
...
$newArray[] = array_combine($firstRow, $row);
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.