doulan1866 2009-11-01 11:02
浏览 59
已采纳

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

I have a binary, the database table of relationships looks like this:

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

I am able to extract or children of for example 1 - but I have very clumsy function for that, so I need something that works better.

The output I need should look like this:

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
        )

)

So far I came up with this function, however it returns nested array, I want it flattened ... but whenever I tried it it just fails.

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

What do I do wrong there?

  • 写回答

1条回答 默认 最新

  • dqlhsm9820 2009-11-01 13:03
    关注

    I want it flattened

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

    instead add each of the items in the return value separately:

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

    (Also shouldn't $topchild be initialised inside the loop?)

    If you are doing a lot of recursive queries like this, a parent-child relation table is not a good choice of data structure. Consider one of the hierarchically-oriented solutions such as nested sets.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?