How to Flatten a Multidimensional Array?
You can use array_walk_recursive()
function in PHP to flatten a multidimensional array. This function will recursively iterate through the array and apply a user-defined function to each element. You can use a closure function to store the flattened array as a reference and append each value of the original array to it.
Here is an example of how you can use array_walk_recursive()
to flatten a multidimensional array:
<?php
$input_array = [1, 2, [3, 4, [5, 6]], [7, 8]];
$flattened_array = [];
array_walk_recursive($input_array, function($a) use (&$flattened_array) {
$flattened_array[] = $a;
});
print_r($flattened_array);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
Alternatively, you can use iterator_to_array()
function to flatten the multidimensional array. This function converts an iterator to an array. You can use RecursiveIteratorIterator
class to create an iterator that can traverse a multidimensional array recursively and pass it to iterator_to_array()
function.
Here is an example of how you can use iterator_to_array()
to flatten a multidimensional array:
<?php
$input_array = [1, 2, [3, 4, [5, 6]], [7, 8]];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($input_array));
$flattened_array = iterator_to_array($iterator, false);
print_r($flattened_array);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )