dongshi6969 2011-12-01 12:24
浏览 42
已采纳

mysql中的父子关系

I am having a table like the following,need to display as Parent and child format

--------------------------------------------------------
    id   role_name   role_id   parent_id
--------------------------------------------------------
    1     NSM           1        0
    2     MR            5        2
    3     ASM           4        3
    4     ZSM           3        4
    5     RSM           2        1
---------------------------------------------------------

the result is like to be the following

NSM
  ---RSM
     -----ZSM
          -----NSM
               -----MR

NSM->ROOT
 RSM->FIRST CHILD
  ZSM->SECOND CHILD
   NSM->THIRD CHILD
    MR->LEAF
  • 写回答

3条回答 默认 最新

  • doutuo3935 2011-12-01 12:37
    关注
    // Fetch all the roles
    $result = mysql_query("select * from roles");
    $roles = array();
    while( $role = mysql_fetch_assoc($result) ) {
        $roles[] = $role;
    }
    
    // Function that builds a tree
    function build_tree($roles, $parent_id=0) {
        $tree = array();
        foreach ($roles as $role) {
            if ($role['parent_id'] == $parent_id) {
                $tree[] = array(
                    'role' => $role,
                    'children' => build_tree($roles, $role['parent_id'])
                );
            }
        }
    
        return $tree;
    }
    
    // Function that walks and outputs the tree
    function print_tree($tree) {
        if (count($tree) > 0) {
            print("<ul>");
            foreach($node in $tree) {
                print("<li>");
                htmlspecialchars($node['role']['role_name']);
                print_tree($node['children']);
                print("</li>");
            }
            print("</ul>");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题