PHP recursively traverse object tree [closed]

青春壹個敷衍的年華 提交于 2020-01-03 17:04:10

问题


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;
}

回答1:


Collects all the apples of a specific branch using a DFS:

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



回答2:


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

@TimCooper's answer will only fetch you first generation children while this slight modification on his answer will get you the apples for all children and the children of children (based on my reading of the question this is what I understood you were needing).

You can check a sample here: http://phpfiddle.org/main/code/9dk-zjc

EDIT NOTE: At the time this answer was written @TimCooper's answer was not complete - now as it stands they are identical.



来源:https://stackoverflow.com/questions/16108512/php-recursively-traverse-object-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!