简体   繁体   中英

Parent child Relationship in 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
// 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>");
    }
}

SQL Results are always flat - you'll not be able to return a hierarchy view of that data in a query.

Instead, I would suggest using whichever client components you are using to show that (is it a tree? what exactly?) that knows how to go thru a flat list and build a hierarchy out of that.

If you want to print a view like that in a console (why would you ever want to do that?), you could do like this:

$data = array();
$query = mysql_query("SELECT * FROM table ORDER BY parent_id");
while($array = mysql_fetch_assoc($query))
{
  $data[$array['parent_id']][] = $array;
}

function output_hierarchy($id, $prepend)
{
  $current = $data[$id];
  foreach($current as $item)
  {
    print $prepend . " " . $item['role_name'];
    if(count($data[$item['id']]) > 0)
    {
      output_hierarchy($item['id'], $prepend . "--");
    }
  }
}

output_hierarchy(0, '');

If you want to use this on your website, you can easily adapt it. Code should be self-explanatory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM