問題描述
我有一個像下面這樣的遞歸函數.
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 循環的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!