Skip to content
Advertisement

Collect all values in a multidimensional array with a specific key

I have an array like this:

[
    [
        'id' => 13,
        'children' => [
            ['id' => 14, 'parent_id' => 13],
            ['id' => 15, 'parent_id' => 13],
        ]
    ]
]

How can I get all [id] values from this array and store them in a flat array like this:

[13, 14, 15]

Advertisement

Answer

$a is your original array.

array_merge(array($a['id']),
            array_map(function($child) { return $child['id']; }, $a['children']));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement