sql >> Base de Datos >  >> RDS >> Mysql

PHP y MySQL Cómo mostrar categorías y subcategorías de la base de datos

Por supuesto que es posible. Este código generará un <ul> <li> árbol jerárquico, independientemente del número de niveles

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

El HTML resultante para su ejemplo será:

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

Eso se mostrará en un navegador como este:

  • a &w
    • c y a veces y
    • re
  • b &f

Repito, esto funciona para cualquier nivel de anidamiento. Espero que esto ayude.