簡體   English   中英

使用php和mysqli的子菜單輸出菜單

[英]Output menu with submenu using php and mysqli

我正在嘗試使用MySQLi和PHP輸出HTML菜單和子菜單。

我的經驗還不足以解決這個問題。

我可以幫忙嗎?

我有以下表格結構頁面:

CREATE TABLE `pages` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `page_name` varchar(255) NOT NULL,
  `parent_id` int(100) NOT NULL,
  `link` varchar(255) NOT NULL,
  `target` varchar(255) NOT NULL,
  `enabled` int(1) NOT NULL DEFAULT '1',
  `sort` int(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

記錄:

INSERT INTO `pages` VALUES ('1', 'Home', '0', 'index.php', '_self', '1', '1');
INSERT INTO `pages` VALUES ('2', 'Team', '0', 'team.php', '_self', '1', '2');
INSERT INTO `pages` VALUES ('3', 'Posts', '0', 'posts.php', '_self', '1', '3');
INSERT INTO `pages` VALUES ('4', 'Programs', '0', 'programs.php', '_self', '1', '4');
INSERT INTO `pages` VALUES ('5', 'Program Name 1', '4', 'program1.php', '_self', '1', '1');
INSERT INTO `pages` VALUES ('6', 'Program Name 2', '4', 'program2.php', '_self', '1', '2');
INSERT INTO `pages` VALUES ('7', 'Program Name 3', '4', 'program3.php', '_self', '1', '3');
INSERT INTO `pages` VALUES ('8', 'Contact', '0', 'contact.php', '_self', '1', '8');

我的目標是輸出類似的東西:

Home
Team
Posts
Programs
--Program Name 1
--Program Name 2
--Program Name 3
Contact

謝謝

我要把細節留給自己,但它會是這樣的。 遞歸是關鍵字:

function getMenu($parent=0, $depth=0){
    $menu = "<ul>"; // each section gets wrapped in UL
    // Select and query to get only the direct childs from $parent:
    $qItems = "SELECT id, page_name FROM pages WHERE parent=".$parent;
    $sItems = mysqli_query($conn, $qItems);
    // This will be the magic part:
    while($fItems = $sItems->fetch_assoc() ){
        $menu.= '<li>';
        $menu.= str_repeat('-', $depth).' '.$fItems['page_name'];
        $menu.= getMenu( $fItems['id'], $depth+1); // <- this is the magic! This will get the childs of this item
        $menu.= '</li>';
    }

    $menu.= "</ul>"; // each section gets wrapped in UL
    return $menu; // return it
}

echo getMenu(); // Do something with it :)

我在這個例子中添加了$depth ,所以破折號到位,以顯示如何找到進入遞歸的方式
編輯 :小但重要的注意事項:如果你繼續向孩子們添加孩子,這將會無休止地繼續... ,無需更新代碼。 這是遞歸的強大力量之一

上面的答案是比我更好的任何一天,但我記得有一個我被困在用select2填充這樣的列表作為多選項,然后再用bootstrap ul li系統,有時你可能需要在數組中的菜單系統填充不同,只是你需要的另一種方式。! 快樂的編碼! :)

while($data = $mysqli_result->fetch_assoc())
{
    if ($data['parentId'] == 0)
    $menu[$data['id']] = $data['page_name'];
    else
    $subMenu[$data['parentId']][$data['id']]=$data['page_name'];
}
foreach($menu as $k=>$m)
{
    //echo $m here as you like..!
    if(isset($submenu[$k]))
    {
        foreach($submenu[$k] as $sub)
        {
            //do with the submenu.
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM