Combine multidimensional array values ​​into a single row in CSV file using PHP
P粉186904731
P粉186904731 2024-03-29 19:55:47
0
1
328

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粉186904731
P粉186904731

reply all(1)
P粉803444331

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!