我正在寻找一些像这里这样的多个垂直菜单。我不想要任何下拉菜单。我在我的 mysql 数据库中为类别使用典型的闭包表层次结构(祖先/后代/深度),我想渲染它们。要从数据库中获取所有父母和孩子,我有以下方法:
public function getSubtree($node) {
$tree = $this->connection->query("
SELECT c.*, cc2.ancestor, cc2.descendant, cc.depth
FROM
category c
JOIN category_closure cc
ON (c.cat_id = cc.descendant)
JOIN category_closure cc2
USING (descendant)
WHERE cc.ancestor = $node AND cc2.depth = 1
ORDER BY cc.depth, c.cat_id);
return $this->parseSubTree($node, $tree);
}
private function parseSubTree($rootID, $nodes) {
// to allow direct access by node ID
$byID = array();
// an array of parrents and their children
$byParent = array();
foreach ($nodes as $node) {
if ($node["cat_id"] != $rootID) {
if (!isset($byParent[$node["ancestor"]])) {
$byParent[$node["ancestor"]] = array();
}
$byParent[$node["ancestor"]][] = $node["cat_id"];
}
$byID[$node["cat_id"]] = (array) $node;
}
// tree reconstruction
$tree = array();
foreach ($byParent[$rootID] as $nodeID) { // root direct children
$tree[] = $this->parseChildren($nodeID, $byID, $byParent);
}
return $tree;
}
private function parseChildren($id, $nodes, $parents) {
$tree = $nodes[$id];
$tree["children"] = array();
if (isset($parents[$id])) {
foreach ($parents[$id] as $nodeID) {
$tree["children"][] = $this->parseChildren($nodeID, $nodes, $parents);
}
}
return $tree;
}
在演示者中,我刚刚:
$this->template->categories = $this->category->getSubtree(1);
因为我使用的是 Nette 框架,所以我使用的是 Latte 模板引擎,这与 Smarty 非常相似。为了与父母和孩子一起渲染所有类别,我有这个:
<ul class="tree">
{block #categories}
{foreach $categories as $node}
<li>
<span">{$node["name"]}</span>
<ul n:if="count($node['children'])">
{include #categories, 'categories' => $node["children"]}
</ul>
</li>
{/foreach}
{/block}
</ul>
我最大的问题是如果我想要三层或更多级别的菜单,如何制作 css 样式。如果选择了某个类别,则显示他的子类别,而隐藏另一个类别。当被选中时,一些子类别显示他的子类别而另一个子类别隐藏等等。真的感谢您的提前,我很抱歉我的英语。希望你知道我的意思。