问题描述
我有一个递归函数,如下所示.
I have a recursive function like below.
public function findnodeintree($cats,$cat_id)
{
foreach($cats as $node)
{
if((int)$node['id'] == $cat_id)
{
echo "finded";
$finded = $node;
break;
}
else
{
if(is_array($node) && array_key_exists('children', $node)){
$this->findnodeintree($node['children'],$cat_id);
}
}
}
return $finded;
}
举例
$node =$this->findnodeintree($category_Array, 169);
它给了我
"founded"
遇到了 PHP 错误
Severity: Notice
Message: Undefined variable: finded
数组结构就像
[0] => Array
(
[id] => 0
[name] => MAIN CATEGORY
[depth] => 0
[lft] => 1
[rgt] => 296
[children] => Array
(
[0] => Array
(
[id] => 167
[name] => CAT 0
[depth] => 1
[lft] => 2
[rgt] => 17
[children] => Array
(
[0] => Array
(
[id] => 169
[name] => CAT 1
[depth] => 2
[lft] => 3
[rgt] => 4
)
[1] => Array
(
[id] => 170
[name] => CAT 2
[depth] => 2
[lft] => 5
[rgt] => 10
[children] => Array
(
[0] => Array
(
[id] => 171
[name] => CAT 5
[depth] => 3
[lft] => 6
[rgt] => 7
)
[1] => Array
(
[id] => 172
[name] => CAT 3
[depth] => 3
[lft] => 8
[rgt] => 9
)
)
)
推荐答案
要从递归中得到正确的值,你的递归调用不能丢弃返回值.而且,由于您想在命中后立即返回递归树,并实际返回匹配的节点,因此您也必须在该点中断循环.
To get the right value from recursion, your recursion call must not discard the return value. And since you want to walk back up the recursion tree as soon as you get a hit, and actually return the matching node, you have to break your loop at that point too.
否则后续的递归调用会覆盖您的变量并返回错误的节点、false
或 null
.
Otherwise subsequent recursion calls overwrite your variable and the wrong node, false
, or null
is returned.
这应该是有效的:
public function findnodeintree($cats,$cat_id)
{
foreach($cats as $node)
{
if((int)$node['id'] == $cat_id){
return $node;
}
elseif(array_key_exists('children', $node)) {
$r = $this->findnodeintree($node['children'], $cat_id);
if($r !== null){
return $r;
}
}
}
return null;
}
注意:我删除了 is_array
因为此时 $node
必须是一个数组或在第一个分支条件下抛出错误.
Note: I removed the is_array
because at that point $node
has to be an array or throw an error at the first branch condition.
这篇关于Php 不会在递归 foreach 循环中中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!