How to Flatten Multidimensional Array in PHP

Tags: April 3, 2018 6:03 AM
0 comments

Goals

Turn PHP multi-dimensional array into one dimensional array (Flatten).

Solution

We will use Standard PHP Library (SPL) to tackle the problem. Assume we have an array like below.

$origin = [
    'Level 1',
    '_2_' => [
        'Level 2',
        '_3_' => [
            'Level 3',
            '_4_' => [
                'Level 4',
                '_5_' => [
                    'Level 5'
                 ]
            ]
        ]
   ],
   'Another Level 1',
   '_2_1' => [
       'Another Level 2'
   ]
];

Turn it into one dimensional array by using SPL RecursiveIteratorIterator and RecursiveArrayIterator class.

Share on Facebook Twitter