PHP
Flattening a Multi-dimensional Array into a Single-level Array
Learn to flatten complex multi-dimensional PHP arrays into a simple, single-level array using a recursive function, ideal for data processing.
<?php
function flattenArray(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, 8]]],
9
];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
How it works: This snippet provides a recursive function `flattenArray()` designed to convert any multi-dimensional array into a single-level array. It iterates through each element; if an element is itself an array, it recursively calls `flattenArray()` on it and merges the results. Otherwise, it simply adds the element to the result array. This is a powerful technique for simplifying nested data structures.