Sometimes we need to traverse an array and group / merge the indexes so that it is easier to extract them so that they are related in the iteration.
<?php
$people = [
['id' => 1, 'name' => 'Hayley'],
['id' => 2, 'name' => 'Jack', 'dad' => 1],
['id' => 3, 'name' => 'Linus', 'dad' => 4],
['id' => 4, 'name' => 'Peter'],
['id' => 5, 'name' => 'Tom', 'dad' => 4],
];
// We set up an array with just the children
function children($dad, $people)
{
$children = [];
foreach ($people as $p) {
if (!empty($p["dad"]) && $p["dad"] == $dad["id"]) {
$children[] = $p;
}
}
return $children;
}
$family = [];
// We merge each child with its respective parent
foreach ($people as $p) {
$children = children($p, $people);
if ($children != []) {
$family[] = array_merge($p, ["children" => $children]);
}
}
print_r($family);
?>
//OUTPUT
Array
(
[0] => Array
(
[id] => 1
[name] => Hayley
[children] => Array
(
[0] => Array
(
[id] => 2
[name] => Jack
[dad] => 1
)
)
)
[1] => Array
(
[id] => 4
[name] => Peter
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => Linus
[dad] => 4
)
[1] => Array
(
[id] => 5
[name] => Tom
[dad] => 4
)
)
)
)