Implode vs使用逗号连接多维数组

时间:2015-03-15 08:58:42

标签: php arrays

我是阵列多维...

Array ( 
    [123] => Array ( [0] => 120 [1] => 200 [2] => 180 [3] => 130 ) 
    [124] => Array ( [0] => 150 [1] => 155 [2] => 160 [3] => 165 ) 
    [125] => Array ( [0] => 121 [1] => 120 [2] => 121 [3] => 121 ) 
)

我想像这样转换

120,200,180,130
150,155,160,165
121,120,121,121

如何编码这些家伙?

我的代码来自stackoverflow ..

 echo join("','", array_map(function ($data) { return $data[0]; }, $data)) 

但是..输出 120, 150, 121 ..我想从123获得

3 个答案:

答案 0 :(得分:1)

这应该适合你:

(这里我只是通过array_map()implode()来检查每个innerArray并打印出来)

<?php

    $arr = [ 
            "123" => [120, 200, 180, 130], 
            "124" => [150, 155, 160, 165], 
            "125" => [121, 120, 121, 121] 
        ];


    array_map(function($v){
        echo implode(",", $v) . "<br />";
    }, $arr);

?>

输出:

120,200,180,130
150,155,160,165
121,120,121,121

答案 1 :(得分:1)

您可以简单地遍历$arrs中的所有项目,并使用implode格式化每个数组:

$arrs = Array ( 
    123 => Array ( 0 => 120, 1 => 200, 2 => 180, 3 => 130 ),
    124 => Array ( 0 => 150, 1 => 155, 2 => 160, 3 => 165 ),
    125 => Array ( 0 => 121, 1 => 120, 2 => 121, 3 => 121 ),
)
foreach($arrs as $arr) {
   echo implode(",",$arr)."\n";
}

"\n"表示您在原始文本中添加新行。如果您想使用HTML进行格式化,您应该明显使用<br/>

foreach($arrs as $arr) {
   echo implode(",",$arr).'<br/>';
}

答案 2 :(得分:0)

$newArr = array();
foreach($yourArr as $key =>$val)
{
   $newArr[] = implode(",",$val);
}
foreach($newArr as $arr)
{
  echo $arr."<br>";
}

<强>输出

120,200,180,130
150,155,160,165
121,120,121,121