TARA
TARA

Reputation: 527

Implode or join multidimentional array with comma

I've array multidimentional ..

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 ) 
)

I want to convert like this

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

how to code this guys ?

my code from stackoverflow too ..

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

but .. the output 120, 150, 121 .. i want to get from 123

Upvotes: 2

Views: 167

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can simply iterate over all items in the $arrs and use implode to format every single array:

$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" means you append a new line in raw text. In case you want to use HTML for formatting, you should evidently use <br/>:

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

Upvotes: 1

Sadikhasan
Sadikhasan

Reputation: 18600

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

output

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

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

This should work for you:

(Here I just go through each innerArray with array_map() and implode() it and print it)

<?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);

?>

Output:

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

Upvotes: 1

Related Questions