[英]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.