Reputation: 693
I have an array that have children that can have more children and so on indefinitely. I need to get id of all parents and childrens.
I tried traversing the array with a function that calls itself but it did not work. I tried: (initial tree is array before mentioned)
public function recursiveTree($tree,$data = NULL){
$data[] = $tree['id'];
if($tree['children']){
foreach ($tree['children'] as $key => $treeChildMin){
return $this->recursiveTree($treeChildMin,$data);
}
}else{
return $data;
}
}
It returns array { [0]=> int(3) [1]=> int(4) [2]=> int(5) }
An example input array would be the following. In that example I want an array with all id for example $values = [3,4,5,7,8,9,10,11];
.
`array(5) {
["id"]=>
int(3)
["children"]=>
array(2) {
[0]=>
array(5) {
["id"]=>
int(4)
["children"]=>
array(2) {
[0]=>
array(5) {
["id"]=>
int(5)
["children"]=>
array(0) {
}
}
[1]=>
array(5) {
["id"]=>
int(7)
["children"]=>
array(0) {
}
}
}
}
[1]=>
array(5) {
["id"]=>
int(8)
["children"]=>
array(3) {
[0]=>
array(5) {
["id"]=>
int(9)
["children"]=>
array(0) {
}
}
[1]=>
array(5) {
["id"]=>
int(10)
["children"]=>
array(0) {
}
}
[2]=>
array(5) {
["id"]=>
int(11)
["children"]=>
array(0) {
}
}
}
}
}
}
Upvotes: 2
Views: 85
Reputation: 41820
Couple of problems with your code:
So you need to only add the id if it exists, and instead of returning inside the loop, add the ids from each child to an array and merge them all together for your returned value.
function get_all_ids($array) {
// add id conditionally
$ids = isset($array['id']) ? [[$array['id']]] : [];
// accumulate ids from all children recursively
// note that you don't need an if here. If children is empty the loop won't execute
foreach ($array['children'] as $child) {
$ids[] = get_all_ids($child);
}
// return merged results
return array_merge(...$ids);
}
Upvotes: 1