递归结果堆栈

时间:2011-01-30 15:28:41

标签: php function recursion stack

将这个递归函数的结果传递回去的最简洁方法是什么?

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;

}
?>

3 个答案:

答案 0 :(得分:1)

您应该使用返回值$count

更新recursion_trigger变量
if(!empty($input)){
    $count = recursion_trigger($input,$count);
}

编辑:

希望以下内容可以帮助您了解它的工作原理:

recursion_trigger ( array("This", "Is", "A", "Sample"), 0)
  recursion_trigger ( array("This", "Is", "A"), 1)
    recursion_trigger ( array("This", "Is"), 2)
      recursion_trigger ( array("This"), 3)
        recursion_trigger ( array(), 4)

答案 1 :(得分:1)

你想的方式可能是$count持久的,而不是因为价值的呼唤。此版本使用引用也可以。

function recursion_trigger($input, &$count = 0){

        if(!empty($input)){
                array_pop($input);
                $count++;
                if(!empty($input)){
                recursion_trigger($input,$count);
                }
        }

echo $count;
return $count;


}

答案 2 :(得分:1)

我猜你真正需要的不是计算数组中元素的数量。

当你做这样的递归函数时,如果它们是尾递归的话,它对性能有好处(事实上,我不确定php是否有这种优化,我希望如此)。这里你有$ count可以作为累加器但不使用它。

function recursion_trigger ($input, $count = 0)
{
  if (!empty($input)) {
    array_pop($input);
    return recursion_trigger($input, $count + 1);
  }
  return $count;
}

这种方式有效并且是尾递归的: - )。