PHP
Flatten Multidimensional Array to a Single Level
Learn how to efficiently flatten a deeply nested or multidimensional PHP array into a single-level array using a custom recursive function for easier processing.
function flattenArray(array $array): array {
$result = [];
foreach ($array as $element) {
if (is_array($element)) {
$result = array_merge($result, flattenArray($element));
} else {
$result[] = $element;
}
}
return $result;
}
$nestedArray = [1, [2, 3], [4, [5, 6]], 7];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
How it works: This snippet provides a recursive function `flattenArray` that takes any multidimensional array and flattens it into a single-level indexed array. It iterates through each element; if an element is an array, it recursively calls itself and merges the results. Otherwise, it directly adds the element to the result array. This is highly useful for processing data from complex structures.