devlin carnate devlin carnate - 2 months ago 18
PHP Question

Formatting array in PHP for output to csv using fputcsv

I have an array in this format:


That I want to output to csv. The trouble I'm having is getting that array in the right format. When I do:

foreach ($array as $row) {
fputcsv($df, $row);

I only get the integer values. I am missing a column with the names like

Here is the output:


But I want column A to have the names like
and column B to have the values.


fputcsv just outputs the array values; the keys would usually be column names, not additional columns in the row. You need to make an array out of each element's key and value.

foreach ($array as $row) {
    $keys = array_keys($row);
    fputcsv($df, array($keys[0], $row[$keys[0]]));