【发布时间】:2016-06-02 09:44:41
【问题描述】:
已编辑:因为现在我知道这称为递归函数,所以我从这里找到了更多信息:
What is a RECURSIVE Function in PHP?
我可以让 var_dump 为数组工作,但不能让返回函数工作。返回值始终为 NULL。有人可以帮忙吗?
预期结果:
我从 var_dump 得到的是:
array(3) { [0]=> string(23) "-orange" [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);
【问题讨论】: