if somebody is looking for exporting the results from a query with dynamic headers to an array then to csv file you could use the following function :
function exportCSVFile($fieldsNames, $result)
{
$fileName = "result.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$fileName");
header("Pragma: no-cache");
header("Expires: 0");
$stdout = fopen('php://output', 'w');
fputcsv($stdout, $fieldsNames, ',', '"'); // put the headers or fields Names
$resultArray = array();
$tempRowHolder = array();
/*
build the finalized array which will be used to export the result as csv
*/
for ($i = 0; $i < count($result); $i++) {
for ($j = 0; $j < count($fieldsNames); $j++) {
$tempRowHolder[$j] = $result[$i][$fieldsNames[$j]]; // fetch a row by the different fields names
}
/* push the row from the tempRowHolder array to the main array($resultArray) */
array_push($resultArray, $tempRowHolder);
/* clear the temporary array (the holder of the row) to use it fresh in the next iteration */
$tempRowHolder = [];
}
$i = 0;
/* put the finalized array into the csv file */
while ($i < count($resultArray)) {
fputcsv($stdout, $resultArray[$i++]);
}
fclose($stdout);
}
array('ACCESSORIES' => 0, 'ANNUALS' => 0, ...)?