将这个递归函数的结果返回的最简洁的方法是什么?递归结果堆栈
function recursion_trigger($input, $count = 0){
if(!empty($input)){
array_pop($input);
$count++;
if(!empty($input)){
recursion_trigger($input,$count);
}
}
echo $count;
return $count;
}
目前它正在返回最上面的电话当然是一个。
///////作为一个额外的问题,这是完整的功能,你可以在这里使用尾递归吗?输出是一个数组,我正在构建,因为我通过值。
<?php
//Page best viewed from page source
//Takes an array of objects that have ID and Parent and organizes the tree into an array representing a set of objectID's by depth
// poor spelling ahead =P
function level_keys($array,$depth=-1,$level=0,$output=null){
// initialize the functions parameters run once at start and not in subsequent self calls
if($level == 0 && $depth != 0){
$output[][]=0;
$level++;
foreach($array as $key=>$node){
if($node->parent==0){
$output[$level][] = $node->id;
unset($array[$key]);
}
}
unset($key); unset($node);
$level++;
$depth--;
}
// set recursion loop and run main part of function
if ( !empty($array) && $depth != 0){
echo 'depth:'.$depth."\n";
foreach($output[$level-1] as $parent){
foreach($array as $key=> $child){
if($parent == $child->parent){
$output[$level][] = $child->id;
unset($array[$key]);
}
}
}
unset($id); unset($parent); unset($key); unset($child);
$depth--;
$level++;
if(!empty($array) && $depth !=0){
// make sure to pass the output back out to the top most level
$output = level_keys($array,$depth,$level,$output,$depth_at);
}
}
return $output;
}
?>
谢谢你完全是这样。我明白它为什么可行,但我仍然无法想象它是如何工作的。 – Prospero 2011-01-30 15:36:47
@Doodle:查看更新后的帖子。 – 2011-01-30 15:41:50