1

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?

0

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.