我有一个递归运行的脚本,并且能够显示多个级别的子菜单。问题是这样的:目前我在我的 CMS 中使用两个部分。
类别和文章。
文章可以在类别下,类别可以在其他类别(子类别)下,但文章不能在其他文章下。
目前我的脚本只适用于类别,但如果例如在我的 CMS 中article 1并且category1都在category0我想显示它们,而不仅仅是category1.
在我的数据库中,结构是这样的:
`snm_categories` - contains category data
`id` - the id of a category
parent_id - the id of it's parent category, this is `1` if it has no parent
`snm_content` - contains the article data
`catid` - the id of the category it falls under, in my above example this will be the same id as the parent_id of `category1`
这是我的脚本:
<?PHP
// Get all categories and articles
$menu = "
SELECT cat.id as cat_id, cat.level, cat.parent_id, cat.title as cat_title, cat.alias as cat_alias, cat.published, cat.rgt, cnt.state, cnt.id as content_id, cnt.catid, cnt.title as content_title, cnt.alias as content_alias
FROM snm_categories cat
LEFT JOIN snm_content cnt
ON cnt.catid = cat.id
WHERE cat.id NOT IN (1, 2, 3, 4, 5, 7, 8, 22)
AND cat.published = 1
GROUP BY cat.id
ORDER BY cat.rgt ASC";
$menuconn = $conn->query($menu);
// Create new array
$menuData = array(
'items' => array(),
'parents' => array()
);
// Create new array with `items` and `parents`, which contain cat_id and parent_id
while($menu = $menuconn->fetch_assoc())
{
$menuData['items'][$menu['cat_id']] = $menu;
$menuData['parents'][$menu['parent_id']][] = $menu['cat_id'];
}
// Function to create menu, $parentId is 1 (when categories have no parent and are topcategories)
function buildMenu($parentId, $menuData)
{
$html = '';
if (isset($menuData['parents'][$parentId]))
{
// If parent_id is 1 put a <li> around it (because it's not a subcat) if not put an <ul> around
if($parentId == '1'){
$html = '<li>';
}else{
$html = '<ul class="sub-menu">';
}
郎朗坤
慕斯王