如何从mysql获取分层菜单

发布于 2024-09-06 21:36:56 字数 544 浏览 4 评论 0原文

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

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

,这里有数百个菜单项。为了获取数组中的所有项目,我必须编写一个像这样的递归函数,

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']);
  }   
}

但这会执行数百个查询。这是从数据库获取分层菜单的最佳方法吗?这种方式对mysql的负载大吗?

I have a table having hierarchical menus like

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

and I have 100s of menu items here. In order to get all items in an array I have to write a recursive function like this

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']);
  }   
}

but this executes 100s of queries. Is this the best way to do this, to get hierarchical menus from database? Does this way loads mysql much?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别理我 2024-09-13 21:36:56
$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,值都是直接子项。

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

The root level will be $hierarchy[0]. Keys are items ids and values are all direct children.

烟雨扶苏 2024-09-13 21:36:56

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

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

Take a look at Nested Sets if you don't mind a little more complex solution. Nested Sets have a very good SELECT performance and I assume that selecting is more important here.

With the help of Nested Sets, complex hierarchical data can be managed in a very fashionable and elegant way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文