I have this problem when my code converts multidimensional array to csv.
This is the structure of my array
Array ( [vbas31] => Array ( [enabled] => Array ( [0] => NO ) [registered] => Array ( [0] => NO ) ) [bnmsa1] => Array ( [enabled] => Array ( [0] => YES ) [registered] => Array ( [0] => NO ) [compromised] => Array ( [0] => NO ) ) )
I want to save it to a csv file for reporting purposes like this:
vbas31, enabled, no, registered, no bnmsa1, enabled, yes, registered, no, compromised, no
What I did in the code is this:
$file = fopen('testfile.csv','w'); $keysarr = array_keys($jsonArr); for($i = 0; $i < count($jsonArr); $i++) { foreach($jsonArr[$keysarr[$i]] as $key => $value) { echo $key . " : " . $value[0] . "<br>"; } $new_line = [$keysarr[$i], $key, $value[0]]; fputcsv($file, $new_line); } fclose($file);
But the output is not what I want, this is the output generated by my code:
vbas31, registered, no bnmsa1, compromised, no
It only gets the last data in the array. Can I ask what's wrong with my code and what I'm doing wrong?
I don't like nested loops, nor the answers provided, but look at this:
Your array:
Code:
You can use another
foreach
inside anotherforeach
. :) You can add the keys to the new row first and then iterate over the remaining elements and add them.$row
variables are only used to check the results.The code is very simple, you should be able to analyze it yourself.
The result of the above code is:
greeting.