我想知道如何使用 PHP 和 MySQL 显示我的分层数据来创建我的类别和无尽的子类别?
一个关于我的 PHP 和 MySQL 代码应该是什么样子的快速示例将会有很大帮助。
MySQL 表类别结构
id parent_id category
1 0 a & w
2 0 b & f
3 1 c & sometimes y
4 1 d
当然有可能。这段代码将呈现一个<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>
这将在浏览器中呈现如下:
我再说一遍,这适用于任何级别的嵌套。
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)