I want to create a PHP recursive to store the value as it passes through each node in array.
I have table like that:
I have tried code like this:
$unit_code = $request->input('unit');
$all_unit_code = [];
$node_start = unit::where('unit_code', $unit_code)->first;
$unit_child1 = unit::where('id_parent', $node_start->row_id)->get();
if(count($unit_child1) != 0){
foreach($unit_child1 as $value1){
$unit_child2 = unit::where('id_parent', $value1->id)->get();
if(count($unit_child2) != 0){
// I doit in every level
}else{
array_push($all_unit_code, $value1->unit_code);
}
}
}else{
array_push($all_unit_code, $value1->unit_code);
}
dd($all_unit_code);
I Start in 310 unit code the result like that:
array(
0=>311,
1=>312,
2=>3110,
3=>31101
)
And this the ilustration:
100
/ \
310 410
/ \ / | \
311 312 411 412 413
| /\ / \
3110 4110 4111 4130 4131
|
31101
If I start in node 100 I will get all node bellow 100. If I start in node 410 I will get all node bellow 410 like 411, 412, 413, 4110 etc as well as other nodes.
I have a problem the code is not optimal because if add a new level in tree I should code again. What I want is the code is dynamic and can know if this end of node. How to implement this logic in php code?
Thanks for your contribution
CodePudding user response: