EDITED:从现在开始我知道这被称为递归函数,我从这里找到了更多信息:
What is a RECURSIVE Function in PHP?
我可以让var_dump为数组工作,但无法使返回函数起作用。返回值始终为NULL。有人可以帮忙吗?
预期结果:
我从var_dump得到的是:
array(3){[0] => string(23)“ - range”[1] => string(22)“ - fruit”[2] => string(22)“ - plant”}
CREATE TABLE IF NOT EXISTS `level_test` (
`id` int(11) NOT NULL,
`name` varchar(80) NOT NULL,
`parentid` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `level_test` (`id`, `name`, `parentid`) VALUES
(1, 'plant', 0),
(2, 'fruit', 1),
(3, 'vegetable', 1),
(4, 'apple', 2),
(5, 'orange', 2),
(6, 'tomatoe', 3),
(7, 'cabbage', 3);
ALTER TABLE `level_test`
ADD PRIMARY KEY (`id`);
ALTER TABLE `level_test`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
function find_tree($pdcatid, $tree ="") {
global $con;
if ($tree == '') {
$tree = array();
}
$query_level = "SELECT * from level_test WHERE `id` = $pdcatid";
if ($result = $con->query($query_level)) {
while($row = $result->fetch_array()) {
if ($result->num_rows == 1) {
array_push($tree, '-<a href="'.$row['id'].'">'.$row['name'].'</a>');
if ($row['parentid'] == 0) {
var_dump($tree); // this works
return $tree; // this doesn't
echo 'hello'; // just for troubleshoot which it doesn't echo
} else {
$parentid = $row['parentid'];
find_tree($parentid, $tree);
}
}
}
}
}
$result_tree = find_tree(5);
var_dump($result_tree);
答案 0 :(得分:4)
返回递归find_tree
结果,如下所示:
if ($row['parentid'] == 0) {
var_dump($tree); // this works
return $tree; // this doesn't
echo 'hello'; // just for troubleshoot which it doesn't echo
} else {
$parentid = $row['parentid'];
return find_tree($parentid, $tree); // <-- HERE
}
现在,仅当$row['parentID']
为0时才返回值。如果parentID
不为0,则不返回任何值(NULL)。所有void函数都返回NULL。然后,如果你调用non-void函数递归,你必须在父调用中返回它的结果。