这是我将导航栏存储到会话
的功能function menu($sp_id,$offset = 0, $ulclass, $liclass) {
$menudb =new db;
if($offset == 0)
$_SESSION['nav_menu'].= "<ul class=\"sf-menu\">";
if($sp_id == 0)
{
$sql = "SELECT `label`, `link` , `sp_id` FROM `nav_menu` ORDER BY `sort` ASC LIMIT $offset,100000000000000";
$menudb->query($sql);
while ($row = $menudb->result()->fetch_assoc()) {
$offset++;
$_SESSION['nav_menu'].= "<li class=\"$liclass\"><a href='" . $row['link'] . "'>" . $row['label'] . "</a>";
if($row['sp_id'] != 0){
$_SESSION['nav_menu'].= "<div class=\"mobnav-subarrow\"></div>";
menu($row['sp_id'],$offset, $ulclass, $liclass);
}
else
$_SESSION['nav_menu'].="</li>";
}
}
else
{
$sql = "SELECT `bt_name` AS label FROM `business_sub_type` WHERE `sp_id` = $sp_id OR `sp_id` = 0";
$menudb->query($sql);
$_SESSION['nav_menu'].= "<ul class=\"sf-menu\">";
while ($row = $menudb->result()->fetch_assoc()) {
$_SESSION['nav_menu'].= "<li class=\"$liclass\"><a href='#'>" . $row['label'] . "</a></li>";
}
$_SESSION['nav_menu'].= "</ul></li>";
menu(0,$offset, $ulclass, $liclass);
}
$_SESSION['nav_menu'].= "</ul>";
//here
}
现在我希望我的函数应该在//这里无论何时来/这里都会以任何代价死去。但它会一次又一次地重复自身和会话存储菜单,
如果这是通过将菜单保存到会话来减少加载时间的正确方法,还请指导我吗?感谢
答案 0 :(得分:0)
你甚至不需要递归来做你正在做的事情。如果你有一个多层数据库结构,最初没有设置深度,你应该使用递归。在您的情况下,您似乎只有两个级别:'nav_menu'数据库表和'business_sub_type'数据库表,与第一个相关。您所要做的就是循环浏览'nav_menu',并且每个人都循环访问与之相关的'business_sub_type。
只需将您的功能更改为
function menu() {
$menudb =new db;
$submenu = new db;
$_SESSION['nav_menu'] = "<ul class=\"sf-menu\">";
// get all nav_menu items ordered by 'sort' column
$sql = "SELECT `label`, `link` , `sp_id` FROM `nav_menu` ORDER BY `sort` ASC";
$menudb->query($sql);
while ($row = $menudb->result()->fetch_assoc()) {
$_SESSION['nav_menu'].= "<li class=\"li-menu\"><a href='" . $row['link'] . "'>" . $row['label'] . "</a>";
if($row['sp_id'] != 0){
$_SESSION['nav_menu'].= "<div class=\"mobnav-subarrow\"></div>";
// get all 'business_sub_type' for this nam_menu
$sql = "SELECT `bt_name` AS label FROM `business_sub_type` WHERE `sp_id` = ".$row['sp_id']." OR `sp_id` = 0";
// I am not sure the ' OR `sp_id` = 0' part is correct at all
$submenu->query($sql);
$_SESSION['nav_menu'].= "<ul class=\"sf-menu\">";
while ($row1 = $submenu->result()->fetch_assoc()) {
$_SESSION['nav_menu'].= "<li class=\"li-menu\"><a href='#'>" . $row1['label'] . "</a></li>";
}
$_SESSION['nav_menu'].="</ul></li>";
}
else
{
$_SESSION['nav_menu'].="</li>";
}
}
$_SESSION['nav_menu'].= "</ul>";
}
并回答关于递归的问题。你通过不在内部调用它来停止递归。或者换句话说,定义一个逻辑分支,如果不满足或满足某些条件,则不会自动调用递归函数。