我的递归php函数看起来像那样。它根据父子结构从db表生成菜单
function generateMenu($parent, $level, $menu, $db){
$q = $db->query("select id, name FROM menu WHERE parent = '$parent' AND showinmenu='$menu'");
if($level > 0 && $q->num_rows > 0){
echo "\n<ul>\n";
}
while($row=$q->fetch_object()){
echo "<li>";
echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>';
//display this level's children
generateMenu($row->id, $level++, $menu, $db);
echo "</li>\n\n";
}
if($level > 0 && $q->num_rows > 0){
echo "</ul>\n";
}
}
它有效,但我觉得它无所事事。有什么需要优化的吗?
答案 0 :(得分:0)
我会像这样摆脱一些代码:
function generateMenu($parent, $level, $menu, $db){
$q = $db->query("select id, name FROM menu WHERE parent = '$parent' AND showinmenu='$menu'");
if($level > 0 && $q->num_rows > 0){
echo "\n<ul>\n";
while($row=$q->fetch_object()){
echo "<li>";
echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>';
//display this level's children
generateMenu($row->id, $level++, $menu, $db);
echo "</li>\n\n";
}
echo "</ul>\n";
}
}
答案 1 :(得分:0)
我会节省许多数据库查询,而不是像这样做。这肯定会带来更好的性能:
function generateMenu($parent, $level, $menu, $db){
$q = $db->query("select parent, id, name FROM menu WHERE showinmenu='$menu'");
$elements = array();
while($row=$q->fetch_object()){
$elements[$row->parent][] = $row;
}
_generateMenu($parent, $level, $elements);
}
function _generateMenu($parent, $level, $elements){
if (!array_key_exists($parent, $elements)){
return;
}
if($level > 0){
echo "\n<ul>\n";
}
foreach($elements[$parent] as $row){
echo "<li>";
echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>';
//display this level's children
_generateMenu($row->id, $level+1, $elements);
echo "</li>\n\n";
}
if($level > 0){
echo "</ul>\n";
}
}