PHP& MySQL如何从数据库中显示任何子类别的类别

时间:2011-04-29 05:00:10

标签: php mysql

我想知道如何使用PHP& amp;显示我的分层数据来创建我的类别和无限子类别MySQL的?

我的PHP& MySQL代码看起来应该会有很多帮助。

MySQL表类别结构

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

1 个答案:

答案 0 :(得分:8)

当然有可能。此代码将呈现<ul> <li>层次结构树,无论级别数是多少

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

您的示例生成的HTML将是:

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

这将在这样的浏览器中呈现:

      
  • a&amp; w ^     
              
    • c&amp;有时y
    •         
    • d
    •     
      
  •   
  • b&amp; f

我再说一遍,这适用于任何级别的嵌套。 希望这会有所帮助。