本文介绍了PHP& MySQL如何显示数据库中任何子类别的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何显示层次结构数据,以使用PHP& amp; amp; amp;创建我的类别和无限的子类别. MySQL?

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

关于我的PHP&的简短示例MySQL代码看起来应该会有所帮助.

A quick example of how my PHP & MySQL code should look like would help out a lot.

MySQL表类别结构

MySQL table categories structure

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

推荐答案

当然可以.此代码将渲染<ul> <li>层次树,无论级别数如何

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

您的示例生成的HTML将是:

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有时是y
    • d
    • a & w
      • c & sometimes y
      • d

      我重复一遍,这适用于任何级别的嵌套.希望这会有所帮助.

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

      这篇关于PHP&amp; MySQL如何显示数据库中任何子类别的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 15:55