Not that complex...
$header = array('OrderId','Customer');
foreach ($products as $product) {
$header[] = $product;
}
$tmp = '"' .implode('","',$header) . '"';
fputs($fh, $tmp . "\n");
For your header construction... Then for you line output something similar to:
foreach($header as $key){
if(empty($line[$key])) $line[$key] = NULL;
if(empty($line[$key]) && !empty($line['total'][$key])){
$line[$key] = $line['total'][$key];
}
}
unset($line['total']);
Now you've filled the gaps for non-existent columns, and given values to the existent ones.