【问题标题】:concat tree hierarchie in a recursive PHP function递归 PHP 函数中的 concat 树层次结构
【发布时间】:2017-01-22 16:45:01
【问题描述】:

我有一个包含分层用户的用户表。所以用户可以有一个父用户。我正在尝试返回某个用户的所有子用户 ID 的数组。 我的函数返回“null”。怎么了?

public function userDownline($userid, $result = array()) {
    $dbconn = $this->DBase();
    $children = $dbconn->GetAll('SELECT id FROM users WHERE parent=' . (int)$userid);
    if(count($children) > 0) {
        foreach($children As $k=>$v) {
            if(!in_array($v['id'], $result)) $result[] = $v['id'];
            $this->userDownline($v['id'], $result);
        }
    } else {
        return $result;
    }
}    

【问题讨论】:

    标签: php recursion tree


    【解决方案1】:

    当然它会返回 null,因为你在 block if(count($children)) 中并且没有返回。

    我认为你必须这样做:

    <?php
    public function userDownline($userid, &$result = array())
    {
        $dbconn = $this->DBase();
        $children = $dbconn->GetAll('SELECT id FROM users WHERE parent=' . (int)$userid);
        if (count($children) > 0) {
            foreach ($children As $k => $v) {
                if (!in_array($v['id'], $result)) $result[] = $v['id'];
                $this->userDownline($v['id'], $result);
            }
        }
        return $result;
    }
    

    我在函数签名中添加了引用,并将返回移出条件块。

    但这确实是一种完全低效且危险的方式(因为 - 内存不足,嵌套级别过多和其他异常)。

    有两种更好的方法:

    1. 使用https://neo4j.com/ - 图形数据库 - 适合您任务的最佳选择。
    2. 如果您仍然只想使用 Sql DB - 请阅读 嵌套集模型 http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

    【讨论】:

    • 谢谢 - 我在上述行中添加了一个“返回” - 现在我得到了第一个孩子(1 个记录集,而不是很多)。
    • mikehillyer 网站很棒 - 谢谢!为此 +1。
    • 太棒了 - &$result 成功了!现在它正在工作。非常感谢!
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2013-11-22
    • 2017-02-04
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    相关资源
    最近更新 更多