简体   繁体   中英

PHP Insert multi-dimensional array values in csv

I have the following array. For simplicity, i have only posted one item but it's a big array that contains a huge number of keys and values

Array
(
[Maths] => Array
    (
        [00] => 0
        [01] => 0
        [02] => 0
        [03] => 0
        [04] => 0
        [05] => 0
        [06] => 0
        [07] => 0
        [08] => 0
        [09] => 0
        [10] => 0
        [11] => 0
        [12] => 0
        [13] => 0
        [14] => 0
        [15] => 0
        [16] => 0
        [17] => 9
        [18] => 5128
        [19] => 5763
        [20] => 1734
        [21] => 632
        [22] => 299
        [23] => 190
    )

I would like to put the contents of the array into a csv file which will be structured like this. One line per outer array and conctenate the values of the inner array to it.

So the above array will appear like this. Please bear in mind that it's not a static array. All the information in the array is dynamic

Math,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,5128,5763,1734,632,299,190

Please help

$data=Array(...);
$csv="";
foreach ($data as $key => $value) {
    $csv.=$key.",".implode(",", $value)."\n";
}

if your structure is something like:

array ( key1 => array(), key2 => array() ... ) you could do this:

$csvOutput = "";

foreach ($baseAy as $key => $subAy) {

    $csvOutput.= "\n".$key.",";

    foreach ($subAy as $value) {
         $csvOutput.= $value.",";
    }
}

print_r($csvOutput);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM