我有一个带有分层菜单的表,例如
"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的负载大吗?
$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,值都是直接子项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)