douqian3712 2014-01-09 09:16
浏览 102
已采纳

在PHP中将多维数组插入csv

I have an array which is structured like this

  [cars] => Array
    (
        [0] => 43063
        [1] => 17306
        [2] => 116078
    )

  [houses] => Array
    (
        [0] => 13300
        [1] => 32243
    )

[garage] => Array
    (
        [0] => 13094
        [1] => 30649
    )

 [hotels] => Array
    (
        [0] => 10025
        [1] => 59468
        [2] => 29734
    )

I would like to create a csv file out of that array. My csv file should be structured this way cars,43063,17306,116078 houses,13300,32243,1000 garage,13094,30649,1000 hotels,10025,59468,29734

I have tried several codes, but i am not getting what i want, how can i acheive it in php ?

Here is the var dump of my array

array(4) {
["23"]=>
array(1) {
["cars"]=>
int(43063)
}
[23]=>
array(4) {
["cars"]=>
int(17306)
["houses"]=>
int(13300)
["garage"]=>
int(13094)
["hotels"]=>
int(10025)
}
[22]=>
array(4) {
["cars"]=>
int(116078)
["houses"]=>
int(32243)
["garage"]=>
int(30649)
["hotels"]=>
int(59468)
}
[21]=>
array(1) {
["hotels"]=>
int(29734)
}
}

I would like to have a csv that contains 4 lines, one line for each key (hotels,car,garage,etc..

cars,43063,17306,116078
houses,13300,32243,1000
garage,13094,30649,1000
hotels,10025,59468,29734
  • 写回答

2条回答 默认 最新

  • dougou3871 2014-01-09 09:20
    关注

    Quick and dirty:

    foreach ($arr as $key => $vals) {
        echo $key . implode(",", $vals) . "
    ";
    }
    

    UPDATE:

    $transformed = array();
    foreach ($arr as $item) {
        foreach ($item as $key => $val) {
            $transformed[$key][] = $val;
        }
    }
    foreach ($transformed as $key => $vals) {
        echo $key . implode(",", $vals) . "
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?