鉴于以下结构的每个级别中的成对组,我想找出是否有"循环"连接点。 (如果" b"在0级上匹配" a"在下一级别。)
我使用递归函数来测试它并且它正常工作。但是,当我测试返回值时,它失败了:
代码:
$tracker=array();
array_push($tracker, 0);
if (findloop(1, $candidates[0]['pairs'][0]['b'])){
echo "<h1>a path has been found</h1><pre>";
print_r($tracker);
echo "</pre>";
}else{
echo "<h3>no loop found</h3><pre>";
print_r($tracker);
echo "</pre>";
}
功能:
function findloop($level, $value){ // so far.. only progression...
echo "<p>level $level, $value</p>";
global $candidates;
global $tracker;
foreach($candidates[$level]['pairs'] as $key=>$pair){
if($pair['a']==$value){
array_push($tracker, $key);
if($level==sizeof($candidates)-1){
echo "omgggggg";
return true;
}else{
findloop($level+1, $pair['b']);
}
}
}
}
结果:
level 1, 19
level 2, 15
level 3, 18
omgggggg
no loop found < - - - - - - - function does (?) return true but it fails
Array
(
[0] => 0
[1] => 1
[2] => 0
[3] => 1
)
结构:
Array
(
[0] => Array
(
[angle] => 41.7
[pairs] => Array
(
[0] => Array
(
[a] => 6
[b] => 19
)
[1] => Array
(
[a] => 19
[b] => 6
)
)
)
[1] => Array
(
[angle] => 11.8
[pairs] => Array
(
[0] => Array
(
[a] => 15
[b] => 19
)
[1] => Array
(
[a] => 19
[b] => 15
)
)
)
[2] => Array
(
[angle] => 14.3
[pairs] => Array
(
[0] => Array
(
[a] => 15
[b] => 18
)
[1] => Array
(
[a] => 16
[b] => 17
)
[2] => Array
(
[a] => 17
[b] => 16
)
[3] => Array
(
[a] => 18
[b] => 15
)
)
)
[3] => Array
(
[angle] => 29.5
[pairs] => Array
(
[0] => Array
(
[a] => 6
[b] => 18
)
[1] => Array
(
[a] => 18
[b] => 6
)
)
)
)
答案 0 :(得分:1)
初始回报很好,但是进一步向上的调用并没有得到这个结果。在你的其他地方你需要返回结果:
if($level==sizeof($candidates)-1){
echo "omgggggg";
return true;
}else{
return findloop($level+1, $pair['b']);
}