DB结构是这样的:
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 1',1,16);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 2',2,3);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 3',4,7);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 4',5,6);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 5',8,13);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 6',9,12);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 7',10,11);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 8',14,15);
当我运行此查询时:
SELECT n.title, COUNT(*)-1 AS depth FROM categories AS n, categories AS p WHERE n.lft BETWEEN p.lft AND p.rgt GROUP BY n.lft ORDER BY n.lft;
$result = mysql_query($query);
// Build array
$tree = array();
while ($row = mysql_fetch_assoc($result)) {
$tree[] = $row;
}
之后我可以使用以下功能:
// bootstrap loop
$result = '';
$currDepth = -1; // -1 to get the outer <ul>
while (!empty($tree)) {
$currNode = array_shift($tree);
// Level down?
if ($currNode['depth'] > $currDepth) {
// Yes, open <ul>
$result .= '<ul>';
}
// Level up?
if ($currNode['depth'] < $currDepth) {
// Yes, close n open <ul>
$result .= str_repeat('</ul>', $currDepth - $currNode['depth']);
}
// Always add node
$result .= '<li>' . $currNode['title'] . '</li>';
// Adjust current depth
$currDepth = $currNode['depth'];
// Are we finished?
if (empty($tree)) {
// Yes, close n open <ul>
$result .= str_repeat('</ul>', $currDepth + 1);
}
}
print $result;
谁能告诉我如何在没有的情况下在树上方打印 <ul> and <li>.
。我想使用
为孩子和子孩子准备的打印它......因为我必须将它放在<select>
列表和其他 HTML 标记中
我使用的结构可以在这里看到: Getting a modified preorder tree traversal model (nested set) into a <ul>