Visst är det möjligt. Denna kod kommer att återge en <ul> <li>
hierarkiskt träd, oavsett antal nivåer
<?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
?>
Den resulterande HTML-koden för ditt exempel blir:
<ul>
<li> a & w
<ul>
<li> c & sometimes y </li>
<li> d </li>
</ul>
</li>
<li> b & f </li>
</ul>
Det kommer att återges i en webbläsare så här:
- a &w
- c &ibland y
- d
- b &f
Jag upprepar, detta fungerar för alla nivåer av kapsling. Hoppas detta hjälper.