Why return interrupts recursion and how to avoid it?

I have a recursion that builds a tree of type orgchart.
As the first row of elements is built according to a different logic than the rest, I have two foreach loops: the first builds the first row of items, second is enclosed in a recursive function and building all the remaining rows. But there was a problem. The function adds values to the first loop via the return. And it breaks the recursion: it is only one branch for each element in the first cycle.

How can I replace return, so recursion is not interrupted?
Here is the code
//shows the tree points of the company
 public function tree($id)
 //call the recursion creates a tree of dots
 function recursiveDotAdd($child, $allDots, $id, $companyModel){
 foreach ($allDots->where('parent_id', $child->id) as $child)
 $dataChild= "children: [{ head: '".$child->name."', id: '".$blockId."', contents: 'mystery',".recursiveDotAdd($child, $allDots, $id, $companyModel)." }]";
 return $dataChild;
 foreach ($allDots->where('parent_id', $dotId) as $dot){
 if ($allData==null) {
 id: '".$blockId."',
 contents: 'do not know', ".recursiveDotAdd($dot, $allDots, $id, $companyModel)."
 } else {
 $allData=$allData.", {
 id: '".$blockId."',
 contents: 'do not know', ".recursiveDotAdd($dot, $allDots, $id, $companyModel)."
 /* dump($allDots);*/
 return view('dottree')->with([
 'companyModel'=> $companyModel,

The result: in the dump three elements yXTMuZg.jpg

If you remove the return $dataChild; from the function recursiveDotAdd, the recursion gets all 5 elements
March 20th 20 at 11:41
0 answer

Find more questions by tags PHP