[英]how to get the hierarchical menu from 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. 我这里有100多个菜单项。 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. 但这会执行100次查询。 Is this the best way to do this, to get hierarchical menus from database? 这是最好的方法,从数据库中获取分层菜单吗? Does this way loads mysql much? 这种方式加载mysql多少?
$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]
. 根级别为$hierarchy[0]
。 Keys are items ids and values are all direct children. 键是项ID,值都是直接子项。
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. 嵌套集具有非常好的SELECT
性能,我认为选择在这里更重要。
With the help of Nested Sets, complex hierarchical data can be managed in a very fashionable and elegant way. 借助嵌套集,可以以非常时尚和优雅的方式管理复杂的分层数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.