How to Flatten Multidimensional Array in PHP

Tags: April 3, 2018 6:03 AM

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.

$flat = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($origin)) as $leaf) {
    $flat[] = $leaf;
}
print_r($flat);

We should get flattened array.

Array
(
    [0] => Level 1
    [1] => Level 2
    [2] => Level 3
    [3] => Level 4
    [4] => Level 5
    [5] => Another Level 1
    [6] => Another Level 2
)

Reference

Share on Facebook Twitter

0 comments:

Post a Comment