如何使用PHP动态创建超级下拉菜单?

时间:2015-03-14 12:12:24

标签: javascript php

我需要动态创建超级下拉菜单。我创建了代码,但无法显示如下:http://cdn.tutsplus.com/net/uploads/legacy/819_megamenu/demo/index.html

我研究了其他代码,但没有帮助我。

以下是我的代码:

$result = mysql_query("SELECT id, label, link, parent FROM menu ORDER BY parent, sort, label");

//Create a multidimensional array to conatin a list of items and parents
$menu = array(
    'items' => array(),
    'parents' => array()
);

//Builds the array lists with data from the menu table
while($items = mysql_fetch_assoc($result)) {
    //Creates entry into items array with current menu item id ie. $menu['items'][1]
    $menu['items'][$items['id']] = $items;

    //Creates entry into parents array. Parents array contains a list of all items with children
    $menu['parents'][$items['parent']][] = $items['id'];
}
//echo "<pre>"; print_r($menu);

//Menu builder function, parentId 0 is the root
function buildMenu($parent, $menu) {
    $html = "";

    if(isset($menu['parents'][$parent])) {
        $html .= "<ul id='mega-menu-9' class='mega-menu'>";

        foreach($menu['parents'][$parent] as $itemId) {
            if(!isset($menu['parents'][$itemId])) {
                $html .= "<li><a href='Javascript: void(0);' class='arrow'><span><i class='fa fa-home'></i></span>".$menu['items'][$itemId]['label']."</a><li>";
            }

            if(isset($menu['parents'][$itemId])) {
                $html .= "<li><a href='Javascript: void(0);' class='arrow'><span><i class='fa fa-home'></i></span>".$menu['items'][$itemId]['label']."</a>";
                $html .= buildMenu($itemId, $menu);
                $html .= "</li>";
            }
        }

        $html .= "</ul> \n";
    }

    return $html;
}

2 个答案:

答案 0 :(得分:0)

互联网上有大量的例子。 Here是如何构建类似于您想要的菜单的逐步解释。

我还建议您查找jQuery plugins,因为那里有很多可行的解决方案。

答案 1 :(得分:0)

试试这个,它对我有用:)

    $Testresult = mysql_query("select id,anchordescription,RootMenu,link from MenuTable");
$menu = array(
    'menus' => array(),
    'parent_menus' => array()
);
while ($row = mysql_fetch_assoc($Testresult))
{
    $menu['menus'][$row['id']] = $row;
    $menu['parent_menus'][$row['RootMenu']][] = $row['id'];
}

function buildMenu($parent, $menu)
{
    $html = "";

    if (isset($menu['parent_menus'][$parent]))
    {
        $html .= "<ul id='ulNav'>";
        foreach ($menu['parent_menus'][$parent] as $menu_id)
        {
            if (!isset($menu['parent_menus'][$menu_id]))
            {
                $html .= "<li><a href='" . $menu['menus'][$menu_id]['link'] . "'>" . $menu['menus'][$menu_id]['anchordescription'] . "</a></li>";
            }
            if (isset($menu['parent_menus'][$menu_id]))
            {
                $html .= "<li><a href='" . $menu['menus'][$menu_id]['link'] . "'>" . $menu['menus'][$menu_id]['anchordescription'] . "</a>";
                $html .= buildMenu($menu_id, $menu);
                $html .= "</li>";
            }
        }
        $html .= "</ul>";
    }

    return $html;
}