How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas?

6.5k Views Asked by At

How can I get the list of values from my array:

[data] => Array
        (
            [5] => Array
                (
                    [0] => 19
                    [1] => 18
                    [2] => 20
                )

            [6] => Array
                (
                    [0] => 28
                )

        )

Expected output result string will be: 19,18,20,28

Thanks!

9

There are 9 best solutions below

5
On BEST ANSWER

With one line, no loop.

echo implode(',', call_user_func_array('array_merge', $data));

Try it here.

0
On

try with this..

foreach($data as $dataArr){
    foreach ($subArray as $value) {
        $res[] = $value;
    }
}
echo implode(',', $res);
1
On

Use following code.

$string = '';
foreach($yourarray as $k){
  foreach($k as $l){
     $string. = $l.",";
  }
}
0
On

Just loop over sub arrays. Store values to $result array and then implode with ,

$result = array();
foreach ($data as $subArray) {
    foreach ($subArray as $value) {
        $result[] = $value;
    }
}
echo implode(',', $result);
0
On

Just use nested foreach Statements

$values = array(); 
foreach($dataArray as $key => $subDataArray) {
   foreach($subDataArray as $value) {
       $values[] = $value;
   }
}
$valueString = implode(',', $values);

Edit: Added full solution..

1
On

Use following php code:

$temp = array();
foreach($data as $k=>$v){
    if(is_array($v)){
        foreach($v as $key=>$value){
            $temp[] = $value;
        }
    }
}
echo implode(',',$temp);
1
On
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
    foreach ($array as $array1) {
        echo $array1.'<br>';
    }
}

Try this one. It will help you

0
On

I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.

Code: (Demo)

$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));

Output:

19,18,20,28

To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.

0
On

Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.

Code: (Demo)

$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});

Output:

19,18,20,28

This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)