我有一棵巨大的動態生成的樹。該樹是根據每個元素的“ parent_id”屬性從平面數組生成的。例如,最終結果將如下所示:Array( [0] => Array ( [id] => 70 [name] => Top Corp [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 43 [name] => Department [parent_id] => 70 [children] => Array ( [0] => Array ( [id] => 45 [name] => Building [parent_id] => 43 [children] => Array ( [0] => Array ( [id] => 75 [name] => Office [parent_id] => 45 ) ) )如何僅提取陣列樹的一部分?我應該看什么功能或方法?例如,我怎么說另一個子級別(可能深20-30個級別)現在位于頂部。例如,的偽函數sliceTree(45)應產生以下結果,也就是從樹開始id 45[0] => Array ( [id] => 45 [name] => Building [parent_id] => 43 [children] => Array ( [0] => Array ( [id] => 75 [name] => Office [parent_id] => 45 ) ) )沒有辦法知道樹可以走多深,因此它的解決方案需要遞歸。我曾嘗試循環數組,尋找起始ID,但是我不確定在找到該點之后如何繼續執行。哪個有效,但僅適用于頂級元素。我該如何遞歸并解釋兒童的多個層次?
1 回答

白衣染霜花
TA貢獻1796條經驗 獲得超10個贊
該sliceTree()函數基本上會查找某個確定id值并將其返回。像這樣的東西:
function sliceTree($tree, $branchId)
{
// check all branches
foreach ($tree as $branch) {
// have we found the correct branch?
if ($branch['id'] == $branchId) return $branch;
// check the children
if (isset($branch['children'])) {
$slice = sliceTree($branch['children'], $branchId);
if (isset($slice)) return $slice;
}
}
// nothing was found
return null;
}
如您所見,該例程是遞歸的。代碼未經測試。
我為混合的隱喻感到抱歉:分支機構和子級,但是您是從頭開始的。
此功能比我希望的要復雜一些,因為在您的示例中,children當沒有子代時該鍵不存在。我通常希望它在那里并且該值是一個空數組。
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報
0/150
提交
取消