PHP
Flattening a Multi-Dimensional Array (Simple Level)
Learn a simple, non-recursive method to flatten a multi-dimensional PHP array into a single-dimensional array, useful for consolidating nested data.
<?php
$multiDimensionalArray = [
'item1' => ['apple', 'banana'],
'item2' => ['orange', ['grape', 'kiwi']], // This nested level will remain if only flattening one level deep
'item3' => 'melon',
'item4' => ['berry']
];
$flattenedArray = [];
foreach ($multiDimensionalArray as $value) {
if (is_array($value)) {
$flattenedArray = array_merge($flattenedArray, $value);
} else {
$flattenedArray[] = $value;
}
}
echo "Flattened Array (single level):
";
print_r($flattenedArray);
// Expected result: ['apple', 'banana', 'orange', ['grape', 'kiwi'], 'melon', 'berry']
?>
How it works: This snippet demonstrates how to flatten a multi-dimensional array into a single-dimensional one, specifically handling one level of nesting. It iterates through the input array, and for each element, if it's an array itself, its contents are merged into the `flattenedArray`; otherwise, the element is added directly. This method is straightforward for consolidating data from moderately nested structures without resorting to recursion for deeper levels.