簡體   English   中英

如何從mysql獲取分層菜單

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM