Home >Backend Development >PHP Tutorial >How Can I Flatten a Multidimensional Array into a One-Dimensional Array in PHP?
Unflattening a Multidimensional Array into a One-Dimensional Array
The task of transforming a multidimensional array into a one-dimensional array can be accomplished with the array_reduce function. This function iteratively applies a provided reduction function to an array, accumulating a single result.
For the specific case of flattening a multidimensional array with simple numeric keys, we can leverage the array_merge function as the reduction function. This function takes two arrays and combines them into a single array.
Utilizing array_reduce with array_merge provides a straightforward method for unflattening a multidimensional array into a linear sequence of elements. As an example, consider the following multidimensional array:
$array = array(array('foo', 'bar', 'hello'), array('world', 'love'), array('stack', 'overflow', 'yep', 'man'));
Applying array_reduce($array, 'array_merge', array()) will yield the desired one-dimensional array:
array('foo', 'bar', 'hello', 'world', 'love', 'stack', 'overflow', 'yep', 'man')
This approach effectively collapses the nested structure of the multidimensional array, producing a flattened array suitable for further processing or storage.
The above is the detailed content of How Can I Flatten a Multidimensional Array into a One-Dimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!