代码之家  ›  专栏  ›  技术社区  ›  Ergec

如何从mysql中获取分层菜单

  •  2
  • Ergec  · 技术社区  · 15 年前

    "id" "parent_id" "name"
    1 0 menu
    2 1 item1
    3 2 item1_1
    4 1 item2
    5 4 item2_1
    ...
    ...
    

    我这里有100种菜单。为了得到数组中的所有项,我必须编写这样的递归函数

    getmenu function(parent_id = 1)
    {
      $items = mysql_query("SELECT id FROM table WHERE parent_id = " + parent_id);
      while ($item = msyql_Fetch_assoc($items)) {
        ...here I put them in array and call recursive function again to get sub items...
        getmenu($item['id']);
      }   
    }
    

    但这会执行100次查询。这是从数据库中获取层次菜单的最佳方法吗?这条路走得多吗?

    2 回复  |  直到 15 年前
        1
  •  4
  •   TheTechGuy    7 年前
    $stmt = "SELECT id, parent_id FROM table";
    $items = Array();
    $result = mysql_query($stmt);
    
    while ($line = mysql_fetch_assoc($result)) {
        $items[] = $line;
    }
    
    $hierarchy = Array();
    
    foreach($items as $item) {
        $parentID = empty($item['parent_id']) ? 0 : $item['parent_id'];
    
        if(!isset($hierarchy[$parentID])) {
            $hierarchy[$parentID] = Array();
        }
    
        $hierarchy[$parentID][] = $item;
    }
    

    根级别将是 $hierarchy[0] . 键是项id,值都是直接子项。

        2
  •  4
  •   PaÅ­lo Ebermann    14 年前

    看一看 Nested Sets 如果你不介意更复杂一点的解决方案。嵌套集具有很好的 SELECT 我认为选择在这里更重要。

    在嵌套集的帮助下,可以以一种非常时尚和优雅的方式管理复杂的层次数据。

    推荐文章