How to "flatten" a multi-dimensional array to simple one in PHP?
In PHP, you can use the "array_reduce" function to flatten a multi-dimensional array.
In PHP, you can use the array_reduce function to flatten a multi-dimensional array. This function takes three arguments: the array to be flattened, a callback function that defines how to combine the elements, and an initial value for the accumulator. Here is an example of how to flatten a multi-dimensional array using array_reduce:
Example of flattening a multi-dimensional array with array_reduce in PHP
<?php
function flattenArray($array)
{
return array_reduce(
$array,
function ($carry, $item) {
if (is_array($item)) {
return array_merge($carry, flattenArray($item));
} else {
$carry[] = $item;
return $carry;
}
},
[]
);
}
$multiDimensionalArray = [1, [2, 3], [4, [5, 6]]];
$flattenedArray = flattenArray($multiDimensionalArray);
print_r($flattenedArray);This will output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )Alternatively, you can use a recursive foreach loop with array_merge to flatten the array:
Example of flattening a multi-dimensional array in PHP
<?php
function flatten_array($array)
{
$flat = [];
foreach ($array as $value) {
if (is_array($value)) {
$flat = array_merge($flat, flatten_array($value));
} else {
$flat[] = $value;
}
}
return $flat;
}
$multiDimensionalArray = [1, [2, 3], [4, [5, 6]]];
$flattenedArray = flatten_array($multiDimensionalArray);
print_r($flattenedArray);This will also output the same result as above.