简体   繁体   English

php - 层次结构表中的递归函数

[英]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.目标是例如当我调用recursive([15])正确返回是Array ( [0] => 15 [1] => 4 [2] => 33 [3] => 27 )没关系。

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?但是当我调用recursive([12]) ,正确的输出是Array ( [0] => 12 [1] => 15 [2] => 4 [3] => 33 [4] => 27 )但我得到无限循环,这是因为表 5、12、12 中的最后一行5, 12, 12但我如何避免这种情况? this recursive function is correct?这个递归函数正确吗?

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM