【问题标题】:how to get the hierarchical menu from mysql如何从mysql获取分层菜单
【发布时间】:2011-03-07 08:34:48
【问题描述】:

我有一个具有分层菜单的表格,例如

"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 次查询。这是从数据库中获取分层菜单的最佳方法吗?这种方式加载mysql多吗?

【问题讨论】:

    标签: php mysql hierarchy hierarchical


    【解决方案1】:
    $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,值都是直接子项。

    【讨论】:

    • 这绝对是比我的更好的解决方案。非常感谢。但最后我决定做一些不同的事情。为了执行更少的 SQL,我创建了一个 cron 作业,它以
      • 格式生成所有菜单,并每 5 分钟将它们转储到静态 php 文件中。然后我只包括它们并应用 css。由于时间紧迫,5 分钟就足够了,即使 1 分钟也可以。服务器负载从 80% 下降到 4% 。不错:)
    • 不客气。对于您的解决方案,这是一种“缓存管理”。确实它有很大帮助:)。您也可以使用APC 将层次结构直接存储在内存中。
    【解决方案2】:

    如果您不介意更复杂的解决方案,请查看Nested Sets。嵌套集具有非常好的SELECT 性能,我认为在这里选择更重要。

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

    【讨论】:

    • 我打算建议相同的链接,这是解决问题的一个非常聪明和优雅的解决方案。
    • 我不知道 :) 。聪明的主意:)。可能适用于网站的下一个版本。
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 2010-10-11
    • 2017-09-25
    • 2015-06-27
    • 2020-05-18
    • 2012-12-17
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多