通过parent id 递归获取所有children (php)

Get all children by parent id recursively (php)

我有以下数组:

[
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],
]

我正在尝试通过键(id)递归地获取所有孩子: 例如对于 13只想得到[16, 17, 19], 对于 18 - [20, 21, 22].

每个节点有一个或多个children。

我正在尝试获取这样的项目,但无法正常工作:

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

    return $kids;
}

有人可以为此提供帮助或提示或提供正确的解决方案吗? 谢谢!

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

如果顺序对您很重要,您可以对阵列进行排序

$data = [
    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 ]
];

function search(array $arr, int $parentId): array {
  $keys = array_keys(array_filter($arr, fn($value) => $value['parent_id'] === $parentId));
  foreach ($keys as $key) {
    $keys = array_merge($keys, search($arr, $key));
  }
  return $keys;
}

$result = search($data, 18);