[英]how to get the hierarchical menu from mysql
我有一个像分层菜单一样的表
"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多少?
$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,值都是直接子项。
如果您不介意更复杂的解决方案,请查看嵌套集 。 嵌套集具有非常好的SELECT
性能,我认为选择在这里更重要。
借助嵌套集,可以以非常时尚和优雅的方式管理复杂的分层数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.