I have a multidimensional array and I need to flatten it into a single-dimensional array in PHP. I've tried using array_merge
within a foreach
loop, but it doesn't produce the desired result. Here's an example of the array structure:
$nums = array (
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
This is the code I've attempted, but it returns an empty array:
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
My expectation is to obtain the following result:
$newArr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
What is the correct approach to flatten a multidimensional array into a single-dimensional array in PHP? Is there a more efficient or alternative solution to achieve the desired output? Any help or suggestions would be greatly appreciated.