PHP不会在递归foreach循环中中断 [英] Php doesn't break in a recursive foreach loop
问题描述
我具有如下所示的递归函数。
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循环中中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!