もちろん可能です。このコードは<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&w
- c&時々y
- d
- b&f
繰り返しますが、これはあらゆるレベルのネストで機能します。これがお役に立てば幸いです。