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

About selvam4win

I am Selvam. I am very jolly person and frank one.

Posted on March 25, 2010, in PHP, Uncategorized and tagged , , , , . Bookmark the permalink. 3 Comments.

  1. Simple/brilliant. Thx

  2. Perfect. Big thank`s.

  1. Pingback: NEW | Wordpress Demo

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: