Php doesn#39;t break in a recursive foreach loop(Php 不会在递归 foreach 循环中中断)
问题描述
我有一个递归函数,如下所示.
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 循环中中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Php 不会在递归 foreach 循环中中断
基础教程推荐
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01