我试图使一个菜单,是一个主菜单,去2级深(子菜单和子菜单)。
我以前也用过concat组,但那只是1级深。事实上,这是两个层次的深度真的把我的最佳实践的循环。
CREATE TABLE `database`.`main_menu` ( `main_menu_id` INT(11) NOT NULL AUTO_INCREMENT , `main_menu_name` VARCHAR(255) NOT NULL , PRIMARY KEY (`main_menu_id`)) ENGINE = InnoDB;
CREATE TABLE `database`.`sub_menu` ( `main_menu_id` INT(11) NOT NULL , `sub_menu_id` INT(11) NOT NULL AUTO_INCREMENT , `sub_menu_name` VARCHAR(255) NOT NULL , PRIMARY KEY (`sub_menu_id`)) ENGINE = InnoDB;
CREATE TABLE `database`.`sub_sub_menu` ( `main_menu_id` INT(11) NOT NULL , `sub_menu_id` INT(11) NOT NULL , `sub_sub_menu_id` INT(11) NOT NULL AUTO_INCREMENT , `sub_sub_menu_name` VARCHAR(255) NOT NULL , PRIMARY KEY (`sub_sub_menu_id`)) ENGINE = InnoDB;
INSERT INTO `main_menu` (`main_menu_id`, `main_menu_name`) VALUES (NULL, 'Food'), (NULL, 'Treats')
INSERT INTO `sub_menu` (`main_menu_id`, `sub_menu_id`, `sub_menu_name`) VALUES ('1', NULL, 'Duck'), ('1', NULL, 'Chicken')
INSERT INTO `sub_menu` (`main_menu_id`, `sub_menu_id`, `sub_menu_name`) VALUES ('2', NULL, 'Bacon Bits'), ('2', NULL, 'Dental')
INSERT INTO `sub_sub_menu` (`main_menu_id`, `sub_menu_id`, `sub_sub_menu_id`, `sub_sub_menu_name`) VALUES ('1', '1', NULL, 'In Gravy'), ('1', '2', NULL, 'in Soup')
INSERT INTO `sub_sub_menu` (`main_menu_id`, `sub_menu_id`, `sub_sub_menu_id`, `sub_sub_menu_name`) VALUES ('2', '3', NULL, 'Sticks'), ('2', '4', NULL, 'Chunks')
mysql查询:
SELECT ssm.sub_sub_menu_name as sub_sub_menu_name ,
sm.sub_menu_name as sub_menu_name ,
mm.main_menu_name as main_menu_name ,
ssm.sub_sub_menu_id as sub_sub_menu_id ,
sm.sub_menu_id as sub_menu_id ,
mm.main_menu_id as main_menu_id
FROM main_sub_sub_menu as ssm
LEFT JOIN main_menu as mm
ON mm.main_menu_id = ssm.main_menu_id
LEFT JOIN sub_menu as sm
ON sm.sub_menu_id = ssm.sub_menu_id
ORDER BY ssm.sub_sub_menu_id, sm.sub_menu_id, ssm.main_menu_id
php在此介绍如何将信息分类:
<?php $cat = $getData->get_menu_categories(); //SQL Query above with PDO
$i = 1;
$j = 1;
for($a=0; $a<= count($cat); $a++){
if($i == $cat[$a]['main_menu_id']){
for($j=1; $j < count($cat[$a]['sub_menu_id']); $j++){ // Was getting stuck here because I can't count it unless it is an array
//Would show each submenu name, then I would make another for loop for the sub sub menu
}
}else{
$i++;
}
输出将是
主菜单
子菜单
子菜单
我在列清单 <ul><li>
样式html菜单列表),基本上是一棵树。
3条答案
按热度按时间oewdyzsn1#
像这样设计你的表格,这样你就不必为每个子元素做表格,你可以在里面上到任何级别。
nwlqm0z12#
您需要循环查询结果并打印类似的内容。我已经用破折号来缩进,但是你可以用html来做的更干净。我为任何想帮忙的人做了一把小提琴。https://www.db-fiddle.com/f/sbtyqbnemcem5vx3xwuuaj/0#&togetherjs=wkjd3lwafs
xkrw2x1b3#
我想向大家展示我是如何根据mankowitz的答案将html添加到这个应用程序中的。