PHP以递归方式遍历对象树

时间:2013-04-19 15:47:01

标签: php recursion

我有一个$ branch对象,可以包含其他$ branch对象:

$branch->children(); 

他们每个人都有$苹果作为孩子。

$branch->apples();

如何递归收集$ branch中的所有$ apples?

function collectApples($branch){
    $apples = array();
    ?
    return $apples;
}

2 个答案:

答案 0 :(得分:5)

使用DFS收集特定分支的所有苹果:

function collectApples($branch) {
    $apples = $branch->apples();
    foreach ($branch->children() as $child) {
        $apples = array_merge($apples, collectApples($child));
    }
    return $apples;
}

答案 1 :(得分:1)

function collectApples($branch) {
    $apples = $branch->apples();
    foreach ($branch->children() as $child) 
        $apples = array_merge($apples, collectApples($child));
    return $apples;
}

@TimCooper的答案只会抓住你的第一代孩子,而对他的回答的轻微修改会让你为所有孩子和孩子的孩子提供苹果(基于我对这个问题的解读)我明白你需要的东西。)

您可以在此处查看示例:http://phpfiddle.org/main/code/9dk-zjc

编辑注意:在写这个答案的时候@TimCooper的答案还没有完成 - 现在它们是相同的。