Search code examples
phprecursionyii2infinite-loop

php - recursive function in hierarchy table


I'm trying from table with departments hierarchy, get all childs from specific father department.

table

id | id_department | id_department_manager
 1         15              12
 2          4              15
 3         33              15
 4         27              33
 5         12              12

recursive function

function recursive (array $elements) {

   $arr = $elements;

   foreach ($arr as $value) {
      $departments = DepartmenstDependencies::find()->where(['id_department_manager' => $value])->all();
   }

   foreach ($departments as $department) {
       $arr[] = $department->id_department;
       $arr = recursive($arr);
   }

   return $arr;
}

recursive([12]);

the goal is for example when i call recursive([15]) correct return is Array ( [0] => 15 [1] => 4 [2] => 33 [3] => 27 ) it's ok.

but when i call recursive([12]) the correct output is Array ( [0] => 12 [1] => 15 [2] => 4 [3] => 33 [4] => 27 ) but i get infinite loop, this is because the last line in table 5, 12, 12 but how i advoid this? this recursive function is correct?


Solution

  • Nice quiz. I suppose you don't want the returned array to contain duplicates. Replace

    foreach ($departments as $department) {
        $arr[] = $department->id_department;
        $arr = recursive($arr);
    }
    

    with

    foreach ($departments as $department) {
        if (!in_array($department->id_department, $arr)) {
            $arr[] = $department->id_department;
            $arr = recursive($arr);
        }
    }