Search code examples
phpalgorithmrecursionchildren

Get all children by parent id recursively (php)


I have a following array:

[
12 => ['parent_id' => null],
13 => ['parent_id' => 12],
14 => ['parent_id' => 12],
15 => ['parent_id' => 12],
16 => ['parent_id' => 13],
17 => ['parent_id' => 13],
18 => ['parent_id' => 12],
19 => ['parent_id' => 16],
20 => ['parent_id' => 18],
21 => ['parent_id' => 20],
22 => ['parent_id' => 20],
]

I am trying to get all chidren recursively by key(id): for instance for 13 just want to get [16, 17, 19], for 18 - [20, 21, 22].

Each node has one or more children.

I am trying to get for item like this, but cannot get working properly:

function getRecursiveChildren($id, $items, $kids = [])
{
    foreach ($items as $key => $item) {
        if ($item['parent_id'] === $id) {
            $kids[] = $this->getRecursiveChildren($id, $items, $kids);
        }
    }

    return $kids;
}

Can someone help or maybe hint or provide correct solution for this? Thanks!


Solution

  • function getRecursiveChildren($id, $items): array
    {
        $kids = [];
        foreach ($items as $key => $item) {
            if ($item['parent_id'] === $id) {
                $kids[] = $key;
    
                if ($id !== $key) {
                    array_push($kids, ...getRecursiveChildren($key, $items));
                }
            }
        }
        return $kids;
    }
    

    if order is important for you, you can order the array