DEV Community

Serhii Klochko
Serhii Klochko

Posted on

How to flatten a PHP array

Here is what I was looking for:

function true_flatten(array $array, array $parents = [])
{
    $return = [];
    foreach ($array as $k => $value) {
        $p = empty($parents) ? [$k] : [...$parents, $k];
        if (is_array($value)) {
            $return = [...$return, ...true_flatten($value, $p)];
        } else {
            $return[implode('_', $p)] = $value;
        }
    }

    return $return;
}
Enter fullscreen mode Exit fullscreen mode

Sample array:

$r = [
    'a' => 'value1',
    'b' => [
        'c' => 'value1.1',
        'd' => 'value1.2',
    ],
    'e' => 'value2',
    'f' => [
        'j' => [
            'k' => 'value2.1',
            'm' => 'value2.2',
            'n' => 'value2.3',
        ],
    ],
    'o' => 'value3',
    'p' => [
        'some' => [
            'very' => [
                'deep' => [
                    'item' => [
                        'first',
                        'second',
                    ]
                ]
            ]
        ]
    ],
    'q' => 'value5',
]; // sample data
Enter fullscreen mode Exit fullscreen mode

Output:

{
    "a": "value1",
    "b_c": "value1.1",
    "b_d": "value1.2",
    "e": "value2",
    "f_j_k": "value2.1",
    "f_j_m": "value2.2",
    "f_j_n": "value2.3",
    "o": "value3",
    "p_some_very_deep_item_0": "first",
    "p_some_very_deep_item_1": "second",
    "q": "value5"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)