Blog Archives

PHP – Combine multi dimensional array into single dimensional array

Using user defined function “array_values_recursive” we can combine the multi dimensional array values into single dimensional array.

The function is

function array_values_recursive($ary)  {

$lst = array();
foreach( array_keys($ary) as $k ) {

$v = $ary[$k];
if (is_scalar($v)) {

$lst[] = $v;

} elseif (is_array($v)) {

$lst = array_merge($lst,array_values_recursive($v));

}

}

return $lst;

}

The example is,

$arr = array(

“RE-1″=>array(“10″,”12″),

“RE-3″=>array(

“RE-4″=>array(“5″,”6″),

“RE-7″=>array(“RE-8″=>array(“9″,”10″),”RE-11″=>array(“12″,”13″))

)

);

Output is,
Array
(

[0] => 10
[1] => 12
[2] => 5
[3] => 6
[4] => 9
[5] => 10
[6] => 12
[7] => 13

)

Thanks to PHP: array_values – Manual

Follow

Get every new post delivered to your Inbox.

Join 168 other followers