Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Flatten a Multidimensional Array?

Is it possible, in PHP, to flatten a (bi/multi)dimensional array without using recursion or references?

I'm only interested in the values so the keys can be ignored, I'm thinking in the lines of array_map() and array_values().

like image 388
Alix Axel Avatar asked Aug 23 '09 23:08

Alix Axel


People also ask

How do you flatten a multidimensional array in Python?

By using ndarray. flatten() function we can flatten a matrix to one dimension in python. order:'C' means to flatten in row-major. 'F' means to flatten in column-major.

How do I flatten a multidimensional array in PHP?

– Usage of Implementation of Method 2 $flattened = new RecursiveArrayIterator ($array); $flattened = new RecursiveIteratorIterator ($flattened); $flattened = iterator_to_array ($flattened, FALSE); var_dump ($flattened);


1 Answers

As of PHP 5.3 the shortest solution seems to be array_walk_recursive() with the new closures syntax:

function flatten(array $array) {     $return = array();     array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });     return $return; } 
like image 183
too much php Avatar answered Sep 27 '22 02:09

too much php