问题
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