php - 层次结构中的递归函数 table
php - recursive function in hierarchy table
我正在尝试从 table 使用部门层次结构,从特定父部门获取所有子项。
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])
正确 return 是 Array ( [0] => 15 [1] => 4 [2] => 33 [3] => 27 )
没关系。
但是当我调用 recursive([12])
时,正确的输出是 Array ( [0] => 12 [1] => 15 [2] => 4 [3] => 33 [4] => 27 )
但是我得到了无限循环,这是因为 table 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);
}
}
我正在尝试从 table 使用部门层次结构,从特定父部门获取所有子项。
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])
正确 return 是 Array ( [0] => 15 [1] => 4 [2] => 33 [3] => 27 )
没关系。
但是当我调用 recursive([12])
时,正确的输出是 Array ( [0] => 12 [1] => 15 [2] => 4 [3] => 33 [4] => 27 )
但是我得到了无限循环,这是因为 table 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);
}
}