PHP函数返回NULL而不是数组 [英] PHP function returning NULL instead of array
问题描述
我调用一个执行某些递归并应返回数组的函数。实际上,被调用函数中return语句之前的var_dump表示该数组。但是,调用函数的结果的var_dump显示NULL而不是数组。
I call a function that does some recursion and is supposed to return an array. In fact, a var_dump immediately before the return statement in the called function evinces the array; however, a var_dump of the results from the calling function reveals NULL instead of the array.
这里是调用函数。
<?php
// configuration
require_once("../includes/config.php");
require_once("../includes/getParentNodes.php");
$bottomNode = 17389;
$chain = [];
$chain[] = $bottomNode;
$results = getParentNodes($bottomNode,$chain);
var_dump($results); ?>
这里是被调用的函数。
<?php
function getParentNodes($node, $results)
{
$select = query("SELECT parent_id FROM classifications WHERE node_id = ?", $node);
$parent = implode("",$select[0]);
if (!empty($parent))
{
$results[] = $parent;
getParentNodes($parent,$results);
}
else
{
return $results;
}
}
?>
如果我在返回调用之前放置var_dump,则会得到以下内容。
If I place a var_dump immediately preceding the return call, I get the following.
Array
(
[0] => 17389
[1] => 17386
[2] => 17334
[3] => 16788
[4] => 15157
[5] => 10648
[6] => 3962
[7] => 665
[8] => 39
[9] => 1
)
但是,调用函数中的var_dump会产生NULL。
However, the var_dump in the calling function produces a NULL.
我已经阅读了手册和相关文章,但是没有一个人对此问题有所了解。任何帮助将不胜感激。
I've read the manual and the related posts, but none shed light on this problem. Any help would be much appreciated.
推荐答案
您错过了返回
You're missing a return
in the recursive case.
$results[] = $parent;
return getParentNodes($parent,$results);
这篇关于PHP函数返回NULL而不是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!