gpt4 book ai didi

PHP递归不停止

转载 作者:行者123 更新时间:2023-12-03 18:35:05 26 4
gpt4 key购买 nike

不确定我在这个递归函数上做错了什么。我有一个带有网站树的数组,我正在寻找的页面可以无限​​深。该函数遍历所有可能性,但有时在找到正确的“页面”时不会停止。

数组

$haystack = array(
array("id" => 1,"parent" => 0,"route" => "home","children" => array()),
array("id" => 2,"parent" => 0,"route" => "news","children" => array()),
array("id" => 3,"parent" => 0,"route" => "photography","children" => array(
array("id" => 6,"parent" => 3,"route" => "photography/portraits","children" => array()),
array("id" => 7,"parent" => 3,"route" => "photography/countries","children" => array()),
array("id" => 8,"parent" => 3,"route" => "photography/landscapes","children" => array(
array("id" => 9,"parent" => 8,"route" => "photography/landscapes/city","children" => array()),
array("id" => 10,"parent" => 8,"route" => "photography/landscapes/wilderness","children" => array())
)
)
)
),
array("id" => 4,"parent" => 0,"route" => "about","children" => array()),
array("id" => 5,"parent" => 0,"route" => "contact","children" => array()),
);

递归函数

function recurse($needle = -1, $haystack = NULL){
$_tmp = array();

foreach($haystack as $key => $item)
{
echo $needle ." === ". $item["id"] . "<br/>";

if((string)$item["id"] === (string)$needle){
echo "Found: " . $needle . "<br/><br/>";
$_tmp = $item;
break;
//return $item; <-- this doesn't work either
} else {
$_tmp = recurse($needle, $item["children"]);
}
}
return $_tmp;
}

测试用例:

$test = recurse(3);
print_r($test);

$test = recurse(7);
print_r($test);

$test = recurse(9);
print_r($test);

最后的测试输出:

9 === 1
9 === 2
9 === 4
9 === 7
9 === 8
9 === 11
9 === 12
9 === 13
9 === 14
9 === 15
9 === 3
9 === 9
Found: 9 <-- should stop here, but continues

9 === 5
9 === 6
Array
(
)

最佳答案

它返回但在其他递归框架中继续。例如,调用:1 -> 2 -> 3 -> 4。从 4 返回但 3 (1 -> 2 -> 3) 继续执行循环。

关于PHP递归不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10920977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com