繁体   English   中英

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

[英]php - recursive function in hierarchy table

我正在尝试从具有部门层次结构的表中获取来自特定父亲部门的所有孩子。

桌子

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

递归函数

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

目标是例如当我调用recursive([15])正确返回是Array ( [0] => 15 [1] => 4 [2] => 33 [3] => 27 )没关系。

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

不错的测验。 我想您不希望返回的数组包含重复项。 代替

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

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