Reputation: 23
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!
Upvotes: 2
Views: 1712
Reputation: 330
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
Upvotes: 3
Reputation: 7163
$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);
Upvotes: 1