Home >Backend Development >PHP Tutorial >How Can I Flatten a Multidimensional Numeric-Keyed Array in PHP?
Flattening Multidimensional Arrays into One Dimension
Transforming a multidimensional array into a one-dimensional array can present a challenge, especially when the original array contains only numeric keys. Unlike other approaches that accommodate varying keys, this question specifically addresses the need for flattening multidimensional arrays with simple numeric keys.
Solution:
The solution to this problem lies in utilizing the array_reduce() function along with array_merge() and an empty array as the initial argument. This effectively combines all the sub-arrays recursively into a single flattened array.
Code:
array_reduce($array, 'array_merge', array())
Explanation:
Example:
Consider the following multidimensional array:
$array = array( array(1, 2, 3), array(4, 5, 6) );
Applying the flattening solution:
$flattenedArray = array_reduce($array, 'array_merge', array());
The resulting $flattenedArray will be:
array(1, 2, 3, 4, 5, 6)
The above is the detailed content of How Can I Flatten a Multidimensional Numeric-Keyed Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!