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?
P粉8034443312024-03-30 09:49:25
I don't like nested loops, nor the answers provided, but look at this:
Your array:
$yourArray = [ 'bnas31' => [ 'enabled' => [0 => 'NO'], 'registered' => [0 => 'NO'] ], 'bnmsa1' => [ 'enabled' => [0 => 'YES'], 'registered' => [0 => 'NO'], 'compromised' => [0 => 'NO'] ] ];
Code:
foreach($yourArray as $key1 => $value1) { $row = $key1; $line = [$key1]; foreach ($value1 as $key2 => $value2) { $row .= ','.$key2.','.$value2[0]; $line = array_merge($line, [$key2, $value2[0]]); } echo $row.'
'; }
You can use another foreach
inside another foreach
. :)
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:
bnas31,enabled,NO,registered,NO bnmsa1,enabled,YES,registered,NO,compromised,NO
greeting.