devlin carnate devlin carnate - 1 month ago 14
PHP Question

Formatting array in PHP for output to csv using fputcsv

I have an array in this format:

array

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
ACCESSORIES
.

Here is the output:

csv

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

Answer

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]]));
}