我假设我的循环保持循环并清除我的临时数组,但不确定如何解决这个问题。最后,返回总是空的。
如何正确返回temp
数组?
数据集:
Array(
[0] => Array(
[0] => Array(
[id] => 55
[parent] => 49
)
[1] => Array(
[id] => 62
[parent] => 50
)
[2] => Array(
[id] => 64
[parent] => 51
)
)
[1] => Array(
[0] => Array(
[id] => 49
[parent] => 0
)
)
)
功能:
<?php
$patterns = function($array, $temp = array(), $index = 0, $parent = 0) use(&$patterns) {
if($index < count($array)) {
foreach($array[$index] as $sub) {
if($index == 0 || $parent == $sub['id']) {
$temp[$index] = $sub['id'];
$patterns($array, $temp, $index + 1, $sub['parent']);
}
}
}
if($index >= count($array) && $parent == 0) {
print_r($temp); // correct result does display here!
return $temp; // this return gives no return
}
};
print_r($patterns($dataset));
?>
print_r
返回Array ( [0] => 55 [1] => 49 )
在第8行,仅当$patterns($array, $temp, ...)
的结果不为空时才返回。此外,不要将结果设置为$temp
变量,这样,如果结果为null,就不会覆盖它。
像这样:
$temp2 = $patterns($array, $temp, $index + 1, $sub['parent']);
if (isset($temp2)) {
return $temp2;
}
如果第13行的条件失败,它将返回null,而这不是您想要的结果,所以如果它为null,您必须继续执行。
顺便说一句,我无法重现您的代码,在代码中给出// correct result does display here!
的正确答案。为了使它工作,我不得不改变行5&6至:
foreach($array[$index] as $key => $sub) {
if ($key == 0 || $parent == $sub['id']) {
我还不得不把第13行改成:
if($index >= count($array)-1 && $parent == 0) {
当您修改第6行并在其开头添加"return"时会发生什么?
RETURN $patterns($array, $temp, $index + 1, $sub['parent']);