开发者

PHP & MySQL How to display categories any sub categoires from database

I was wondering how would I display my hierarchical data to create my categories and endless sub categories using PHP & MySQL?

A quick example of how my PHP & MySQL code should look like would help out 开发者_高级运维a lot.

MySQL table categories structure

id  parent_id   category
1   0           a & w
2   0           b & f
3   1           c & sometimes y
4   1           d


Of course it's possible. This code will render a <ul> <li> hierarchical tree, regardless of number of levels

<?php
  //Connect to mysql server
  $cn = mysql_pconnect("server", "username", "password");
  mysql_select_db("database_name");
  $rs = mysql_query("SELECT id, parent_id, category FROM categories", $cn);
  $childrenTree = array(); //Will store an array of children for each parent
  $categoryNames = array(); //Will store category name for each id
  //We fill $childrenTree and  $categoryNames from database
  while($row = mysql_fetch_array($rs)){
     list($id, $parent_id, $category) = $row;     
     $categoryNames[(string)$id] = $category;
     $parent_id = (string)$parent_id;
     if(!array_key_exists($parent_id, $childrenTree)) 
         $childrenTree[$parent_id] = array();
     $childrenTree[$parent_id][] = (string)$id;
  }

 //Main recursive function. I'll asume '0' id is the root node
 function renderTree($parent = "0"){
    global $categoryNames;
    global $childrenTree;
    if($parent != "0") echo "<li> ", $categoryNames[$parent], "\n";
    $children = $childrenTree[$parent];
    if(count($children) > 0){ //If node has children
       echo "<ul>\n";
       foreach($children as $child)
          renderTree($child);
       echo "</ul>\n";
    }
    if($parent != "0") echo "</li>\n";
 }
 renderTree();  //This renders the hierarchical tree
?>

The resulting HTML for your example will be:

<ul>  
  <li> a & w
    <ul>
        <li> c & sometimes y </li>
        <li> d </li>
    </ul>
  </li>
  <li> b & f </li>
</ul>

That will render in a browser like this:

  • a & w
    • c & sometimes y
    • d
  • b & f

I repeat, this works for any level of nesting. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜