亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用PHP提取多維數組樹的一部分

如何使用PHP提取多維數組樹的一部分

PHP
千萬里不及你 2021-04-27 13:10:34
我有一棵巨大的動態生成的樹。該樹是根據每個元素的“ 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當沒有子代時該鍵不存在。我通常希望它在那里并且該值是一個空數組。


查看完整回答
反對 回復 2021-05-28
  • 1 回答
  • 0 關注
  • 178 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號