Flattening Multidimensional Arrays in PHP
Flattening a multidimensional array involves converting its nested structure into a one-dimensional array. This can be achieved in PHP without using recursion or references.
Iterative Solution Using array_walk_recursive()
For PHP versions 5.3 and higher, the most concise solution is to use array_walk_recursive() along with the new closures syntax:
function flatten(array $array) { $return = array(); array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; }); return $return; }
This function traverses the array recursively, storing each encountered value in the $return array. The result is a flattened one-dimensional array containing all the original values.
The above is the detailed content of How Can I Flatten a Multidimensional Array in PHP Without Recursion?. For more information, please follow other related articles on the PHP Chinese website!