PHP
Recursively Flattening a Multi-Dimensional Array
Learn to convert a nested PHP array into a single-dimensional array using a recursive function, useful for simplifying complex data.
<?php
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 = [
'a' => 1,
'b' => [
'c' => 2,
'd' => [
'e' => 3,
'f' => 4
]
],
'g' => 5,
'h' => [['i' => 6], 'j', [7]]
];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
// Another example
$dataMatrix = [
[1, 2, [3, 4]],
5,
[6, [7, 8]],
9
];
$flatMatrix = flattenArray($dataMatrix);
print_r($flatMatrix);
?>
How it works: This snippet provides a custom recursive function `flattenArray` to convert a multi-dimensional PHP array into a single-dimensional array. It iterates through the array, and if an element is itself an array, it calls itself recursively to flatten that sub-array. Non-array elements are directly added to the result. This is useful for processing deeply nested data structures where you need all values at a single level.