2015-09-29 39 views
1

我有以下代码:PHP递归函数没有返回预期

use app\models\Kategorije; 

function hasMoreParent($id,$i = 0){ 
    $model = new Kategorije(); 
    $parent_id = $model::find()->where('id = :id',[':id' => $id])->one()->parent_id; 
    if ($parent_id > 1) { 
     $i++; 
     hasMoreParent($parent_id,$i); 
    } 
     return $i; 
} 

而且,当$ i大于0,它总是返回1而不是2或3 .. 我怎样才能使它返回那些其他数字?

+0

你永远不会捕获递归调用的返回值,所以在顶层,你只会得到返回的FIRST调用的值。你可能需要'$ i + = hasMoreParent(...)'。 –

+0

你能写出例子@MarcB吗? – user3002173

回答

0

您错过了return关键字以实现递归,否则函数hasMoreParent将被执行,但流程将继续并到达return $i;语句。

use app\models\Kategorije; 

function hasMoreParent($id, $i = 0) { 
    $model = new Kategorije(); 
    $parent_id = $model::find()->where('id = :id', [':id' = > $id])->one()->parent_id; 
    if ($parent_id > 1) { 
     $i++; 
     return hasMoreParent($parent_id, $i); 
    } 
    return $i; 
} 
+0

你,先生,刚刚救了我的命!非常感谢! – user3002173

+0

没问题!乐意效劳 :) – taxicala