PHP在csv中插入多维数组值

时间:2014-01-14 09:22:48

标签: php arrays csv multidimensional-array

我有以下数组。为简单起见,我只发布了一个项目,但它是一个包含大量键和值的大数组

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
    )

我想将数组的内容放入一个csv文件中,结构如下。每个外部数组一行,并将内部数组的值连接到它。

所以上面的数组会像这样出现。请记住,它不是静态数组。数组中的所有信息都是动态的

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

请帮忙

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果您的结构类似于:

array(key1 => array(),key2 => array()...) 你可以这样做:

$csvOutput = "";

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

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

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

print_r($csvOutput);