You have a multidimensional array which you want to convert to a one dimensional array.
To solve this, we’ll use iterators which are objects from Standard PHP Library. The Standard PHP Library (SPL) is a collection of interfaces and classes used to solve common problems that web developers face everyday efficiently.
SPL provides a set of iterators to traverse over objects. Two of those are RecursiveArrayIterator and RecursiveIteratorIterator.
The following code show how to flatten a multidimensional array into a single one-
<pre> <?php $month = array( array("January"), array("February"), array("March", "April", array("May", "June")), array("July"), array("August", "September", "October"), array("November", "December") ); $recur_multi_dimen_arr_obj = new RecursiveArrayIterator($months); $recur_flat_arr_obj = new RecursiveIteratorIterator($recur_multi_dimen_arr_obj); $flat_arr = iterator_to_array($recur_flat_arr_obj, false); print_r($flat_arr); ?> </pre>
Output: Array (  => January  => February  => March  => April  => May  => June  => July  => August  => September  => October  => November  => December )
|Line 12||To traverse the nested arrays recursively inside the multidimensional array $month, we use RecursiveArrayIterator class and makes an object($recur_multi_dimen_arr_obj) of it.|
|Line 13||RecursiveIteratorIterator will flatten all the elements of the nested arrays and will make it a single array. Note, RecursiveIteratorIterator acts only on recursive iterators, not on an array. Here, the recursive iterator is $recur_multi_dimen_arr_obj. RecursiveIteratorIterator object will iterate over the RecursiveArrayIterator and will flatten it. If you don’t use this class, you’ll get the root array. To test, inactivate this line and see yourself.|
|Line 14||iterator_to_array() function copies the elements of the iterator into an array. The second parameter ‘false’ ensures that the keys of one nested array will not be replaced by the keys of its previous nested array if there is more than one nested array.|
The code (shorter version):
The above code could be written shortly as –
<pre> <?php $data = array( array("January"), array("February"), array("March", "April", array("May", "June")), array("July"), array("August", "September", "October"), array("November", "December") ); $recur_flat_arr_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($months)); $flat_arr = iterator_to_array($recur_flat_arr_obj, false); print_r($flat_arr); ?> </pre>
Same as above
Note: One of the advantages of using SPL classes is that it can flatten any level of multidimensional array.