Home » Archive

Articles tagged with: array

  Posted: Mar 29 | Filed under: General

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 !