【问题标题】:How to retrieve tree nodes children (recursive function help)如何检索树节点子节点(递归函数帮助)
【发布时间】:2010-12-12 00:41:26
【问题描述】:

我有一个二进制,关系的数据库表如下所示:

+----+----------+---------+-----+
| id | parentID | childID | pos |
+----+----------+---------+-----+
|  1 |        1 |       2 | l   |
|  2 |        1 |       3 | r   |
|  3 |        2 |       4 | l   |
|  4 |        3 |       5 | r   |
|  5 |        4 |       6 | l   |
|  6 |        5 |       7 | r   |
+----+----------+---------+-----+

我可以提取例如 1 的子节点 - 但我的功能非常笨拙,所以我需要一些更好的东西。

我需要的输出应该是这样的:

Array
(
    [0] => Array
        (
            [id] => 2
            [parentID] => 1
            [pos] => l
        )

    [1] => Array
        (
            [id] => 4
            [parentID] => 2
            [pos] => l
        )

    [2] => Array
        (
            [id] => 6
            [parentID] => 4
            [pos] => l
        )

    [3] => Array
        (
            [id] => 3
            [parentID] => 1
            [pos] => r
        )

    [4] => Array
        (
            [id] => 5
            [parentID] => 3
            [pos] => r
        )

    [5] => Array
        (
            [id] => 7
            [parentID] => 5
            [pos] => r
        )

)

到目前为止,我想出了这个函数,但是它返回嵌套数组,我希望它变平......但每当我尝试它时它都会失败。

function children($pid) {
    //set sql
    $sql = "SELECT * FROM relationships WHERE parentID = ".$pid;    
    //save query to result
    $result = mysql_query ($sql)
        or die("Bad request " . mysql_error()); 

    while ($item = mysql_fetch_array($result)):
        $topchild["id"] = $item["childID"];
        $topchild["parentID"]= $item["parentID"];
        $topchild["pos"] = $item["pos"];        

        $children[] = $topchild;
        $children[] = children($item["childID"]);       
    endwhile;


        return $children;
}

我在那里做错了什么?

【问题讨论】:

  • 我不太关注你。你对孩子的定义是什么?节点id=1 只有一个子节点(带有id=2),还是您认为id=1 下的所有节点都是它的子节点?我也不明白你发布的输出。它看起来就像是数据库表的转储。它有什么特别之处?
  • node id=1 有两个(立即)孩子(2,3),那些有另一个孩子(4,5,6,7)......我希望能够得到一个数组看起来像我发布的那个将是给定父级的所有子级,或者通过深度参数指定它(例如 0 = 全部,1 = 一级子级等) - 我可以做到我只是没有将它包含在这个函数中还
  • 错误,查看您的表,我看到的是链表,而不是树:1 指向自身(起点或根),2 指向 1,@987654330 @ 指向 2 等:1 -> 2 -> 3 -> 4 -> 5 -> 6。您的数组输出看起来不同...

标签: php arrays recursion tree binary-tree


【解决方案1】:

我希望它变平

$children[] = children($item["childID"]);  

而是分别添加返回值中的每一项:

foreach (children($item['childID'] as $child)
    $children[]= $child;

(也不应该在循环内初始化$topchild?)

如果你在做很多这样的递归查询,父子关系表不是数据结构的好选择。考虑一种面向层次的解决方案,例如nested sets

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多