如何检索树节点子节点(递归函数帮助)

时间:2009-11-01 11:02:09

标签: php arrays recursion tree binary-tree

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

+----+----------+---------+-----+
| 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;
}

我在那里做错了什么?

1 个答案:

答案 0 :(得分:1)

  

我希望它变平了

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

而是单独添加返回值中的每个项目:

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

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

如果您正在进行大量这样的递归查询,则父子关系表不是数据结构的良好选择。考虑一种面向层次结构的解决方案,例如nested sets