Skip to content
Advertisement

PHP: Write values of associative array in a column of CSV file based on their keys

I have this associative array with a key “key1” and another “key2”:

{   
   id   :   1,
   name : "Rob",
   key1 : "bla"
},
{   
   id   :   2,
   name : "Mat",
   key1 : "blabla"
},
{   
   id   :   3,
   name : "Tom",
   key2 : "blablabla"
}
  

this is my code for write the csv file:

    // $csv is the array

    $fp = fopen('file.csv', 'wb');

    foreach ($csv as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);

result is something like. All the information in line:

1,Rob,bla
2,Mat,blabla
3,Tom,blablabla

Is there a way to write these values in the column based on their key? The result should be:

id  |  name  |  key1    |   key2
1   |  Rob   |  bla     |
2   |  Mat   |  blabla  |
3   |  Tom   |          |  blablabla

Advertisement

Answer

You can do this with a loop saving all your table keys. Then you check all the keys on each line, if the key is missing, create it with an empty string !

$fp = fopen('file.csv', 'wb');
$savedKeys = [] ;
foreach ($csv as $getKey) {
$savedKeys = array_merge($savedKeys,array_keys($getKey)) ;
}

$savedKeys =array_unique($savedKeys) ;

foreach ($csv as $fields) {

    foreach ($savedKeys AS $checkKey){
        if (!isset($field[$checkKey])){
            $field[$checkKey] = '';
        }
    }
    fputcsv($fp, $fields);
}

fclose($fp);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement