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. 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 =开发者_JAVA百科 " + 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?
$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.
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.
精彩评论