【问题标题】:RECURSIVE Function return array as NULL while var_dump before return worksRECURSIVE 函数将数组返回为 NULL,而返回前的 var_dump 有效
【发布时间】: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);

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    返回递归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。然后,如果你调用非 void 函数递归,你必须在父调用中返回它的结果。

    【讨论】:

    • 您应该添加一个简短的说明为什么这是必需的。
    • 您能详细说明一下并给我更多提示吗?你的意思是在循环函数内部?不是返回$tree,而是返回find_tree($parentid, $tree);?因为我刚刚测试了它,它似乎不起作用
    • @arkascha,好的。一秒钟。
    • 天哪!谢谢@maximkou :)
    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多