4

I have got a $branch object that can contain other $branch objects:

$branch->children(); 

Each of them can have $apples as children.

$branch->apples();

How can I collect all of the $apples from the $branch recursively?

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

2 回答 2

5

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

function collectApples($branch) {
    $apples = $branch->apples();
    foreach ($branch->children() as $child) {
        $apples = array_merge($apples, collectApples($child));
    }
    return $apples;
}
于 2013-04-19T15:49:46.680 回答
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 的答案并不完整——现在它们是相同的。

于 2013-04-19T16:46:02.797 回答