My recursive php function looks like that. It generates menu from db table based on parent-child structure
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";
}
}
It works but i feel that it does bunch of work for nothing. Is there anything that needs to be optimized?