我有一个具有分层菜单的表格,如下所示
"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']);
}
}但这会执行100秒的查询。这是从数据库中获取分层菜单的最好方法吗?这种方式加载mysql的次数多吗?
发布于 2010-06-23 22:30:38
$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]。键是项,ids和值都是直接的子项。
发布于 2010-06-23 22:44:36
如果您不介意更复杂的解决方案,请看一下Nested Sets。嵌套集具有非常好的SELECT性能,我认为选择在这里更重要。
在嵌套集合的帮助下,可以以一种非常时髦和优雅的方式管理复杂的分层数据。
https://stackoverflow.com/questions/3102447
复制相似问题