Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning multidimensional array into one-dimensional array [duplicate]

I've been banging my head on this one for a while now.

I have this multidimensional array:

Array (     [0] => Array         (             [0] => foo             [1] => bar             [2] => hello         )      [1] => Array         (             [0] => world             [1] => love         )      [2] => Array         (             [0] => stack             [1] => overflow             [2] => yep             [3] => man         ) 

And I need to get this:

Array (     [0] => foo     [1] => bar     [2] => hello     [3] => world     [4] => love     [5] => stack     [6] => overflow     [7] => yep     [8] => man ) 

Any ideas?

All other solutions I found solve multidimensional arrays with different keys. My arrays use simple numeric keys only.

like image 502
Tomi Seus Avatar asked Dec 23 '11 01:12

Tomi Seus


People also ask

How do I make multiple arrays into one array?

Using concat method The concat method will merge two or more arrays into a single array and return a new array. In the code above, we have merged three arrays into an empty array. This will result in merging multiple arrays into a new array.

How do you merge multidimensional arrays?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

Can you clone a 2D array?

A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.


2 Answers

array_reduce($array, 'array_merge', array()) 

Example:

$a = array(array(1, 2, 3), array(4, 5, 6)); $result = array_reduce($a, 'array_merge', array()); 

Result:

array[1, 2, 3, 4, 5, 6]; 
like image 186
deceze Avatar answered Oct 02 '22 12:10

deceze


The PHP array_merge­Docs function can flatten your array:

$flat = call_user_func_array('array_merge', $array); 

In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:

$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0); 

See as well: How to Flatten a Multidimensional Array?.

like image 33
hakre Avatar answered Oct 02 '22 14:10

hakre