Filed Under: General

Convert multidimensional array into array

29 March 2008 One Comment Tags: , ,


Share

Today I had to convert a multidimensional array and found a very simply solution at PHP.net that I want to share with you.

A multidimensional array is an array that stores arrays. Usually a normal array is easier to handle, that’s why converting the array is a good solution.

That will turn this:

Array
(
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
)
)

Into this simple array:


Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)

Here’s the very efficient and short code:

function flatten_array($value, $key, &$array) {
if (!is_array($value))
array_push($array,$value);
else
array_walk($value, 'flatten_array', &$array);
}

Then you are able to to use “array_walk”, simply rename $oldarray to the name of your multidimensional array!

$newarray = array();
array_walk($oldarray, 'flatten_array', &$newarray);

 

Happy converting !







Like our posts? Then subscribe via Mail:

Email:  

Similar Posts:

One Comment »

  • darrenh said:

    Comparing to what I’ve read about this before, it sounds absolutely impressing. I’m an old internet user, and have read a lot about this kind of stuff, but what I read here today is absolutely different.

Leave your response!

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.com.