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

在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) . "
    ";
    }
    
    点赞 评论
  • dsjmrpym220113739 2014-01-09 09:33

    You could try something like this

    function arrayToValues(array $data)
    {
        $output = array();
    
        foreach ($data as $key => $item) {
            if (is_array($item)) {
                $output = array_merge($output, array($key), arrayToValues($item));
            } else {
                $output[] = $item;
            }
        }
    
        return $output;
    }
    
    $csvData = implode(',', arrayToValues($yourArrayData));
    

    If you want to write the output you could use fputcsv in combination with the function instead.

    点赞 评论

相关推荐 更多相似问题