Create key-value pair from csv php

Viewed 42

I have a csv file like below

tl_blade_thickness,tl_blade
test1,test1
test2,test2
test3,test3
test4,test4
test5,test5
test6,test6
test7,test7
test8,test8
test9,test9

I'm trying to create a key value pair array like below.

["tl_blade_thickness"=>["test1","test2","test3",...],tl_blade=>["test1","test2","test3",...]]

I tried like this below.

$content = fopen("csv.csv", "r");
 $all_rows = array();
 $header = fgetcsv($content);
 while ($row = fgetcsv($content)) {
       $all_rows[] = array_combine($header, $row);
 }
1 Answers

Use the first line of the file to create the keys of the array. Then push each field of the remaining lines into the corresponding element keys.

$content = fopen("csv.csv", "r");
$headers = fgetcsv($content);
$all_rows = array_fill_keys($headers, []);
while ($row = fgetcsv($content)) {
    foreach ($headers as $i => $name) {
        $all_rows[$name][] = $row[$i];
    }
}
Related