开发者

Php recursive function optimization

开发者 https://www.devze.com 2023-04-10 08:25 出处:网络
My recursive php function looks like that. It generates menu from db table based on parent-child structure

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(开发者_JAVA技巧"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?


I would get rid of some of that code like this:

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";
  }
}


I would save on the many database queries and instead do it in one like this. This will definitely result in better performance:

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";
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消