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.
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.
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.
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.
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];
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With