2012-07-09 84 views
1

我想創建動態多級菜單,使用PHP從MySQL數據庫獲取數據。我設法用這種格式命令在一個PHP數組中的菜單項:PHP/MySQL的多級菜單

----------------------- 
Array 
(
[1] => Array 
    (
     [id] => 1 
     [ubicacion] => top_a 
     [nivel] => 1 
     [parent_id] => 
     [tipo] => link 
     [link] => http://www.google.com 
     [titulo] => Google 
     [alias] => google_es 
     [children] => Array 
      (
       [3] => Array 
        (
         [id] => 3 
         [ubicacion] => top_a 
         [nivel] => 2 
         [parent_id] => 1 
         [tipo] => link 
         [link] => http://www.gmail.com 
         [titulo] => Gmail 
         [alias] => gmail 
         [children] => Array 
          (
           [4] => Array 
            (
             [id] => 4 
             [ubicacion] => top_a 
             [nivel] => 3 
             [parent_id] => 3 
             [tipo] => link 
             [link] => www.inbox.gmail.com 
             [titulo] => Inbox 
             [alias] => inbox_gmail 
            ) 

          ) 

        ) 

      ) 
    ) 

[2] => Array 
    (
     [id] => 2 
     [ubicacion] => top_a 
     [nivel] => 1 
     [parent_id] => 
     [tipo] => link 
     [link] => http://www.yahoo.com 
     [titulo] => Yahoo 
     [alias] => yahoo 
    ) 
) 
----------------------- 

的問題是,我無法弄清楚如何輸出數組作爲HTML標記的方式,將與N功水平。我可以用固定數量的水平是這樣做的:

foreach($menu_array as $menu) { 
echo "<li><a href='{$menu['link']}'>{$menu['titulo']}</a>"; 
if (array_key_exists('children',$menu)) { 
    echo "<ul>"; 
    foreach ($menu['children'] as $child_menu) { 
     echo "<li><a href='{$child_menu['link']}'>{$child_menu['titulo']}</a>"; 
     if (array_key_exists('children',$child_menu)) { 
      echo "<ul>"; 
      foreach ($child_menu['children'] as $child2_menu) { 
       echo "<li><a href='{$child2_menu['link']}'>{$child2_menu['titulo']}</a>"; 
      } 
      echo "</ul>"; 
     } 
    } 
    echo "</ul>"; 
} 
echo "</li>"; 
} 

但對於3級這隻作品,我知道應該有解決這個問題的一種方式,我知道我不是第一個面臨多維數組的HTML輸出的問題。

+0

你會介意給出一點背景爲什麼你需要菜單在數據庫中嗎? – 2012-07-09 23:10:54

+0

我正在爲未來的項目做一個自定義的CMS – davidaam 2012-07-10 00:31:59

回答

6

您可以使用一點遞歸來讓您達到更多級別。

function echo_menu($menu_array) { 
    //go through each top level menu item 
    foreach($menu_array as $menu) { 
     echo "<li><a href='{$menu['link']}'>{$menu['titulo']}</a>"; 
     //see if this menu has children 
     if(array_key_exists('children', $menu)) { 
      echo '<ul>'; 
      //echo the child menu 
      echo_menu($menu['children']); 
      echo '</ul>'; 
     } 
     echo '</li>'; 
    } 
} 

echo '<ul>'; 
echo_menu($menu_array); 
echo '</ul>'; 

這將適用於任何您想要的子級別。

+0

直到您達到遞歸限制時爲止的任意級別;) – hakre 2012-07-09 23:20:23

+0

我會稱之爲一個功能。沒有人想要瀏覽那麼多嵌套菜單! ;) – jprofitt 2012-07-09 23:21:47

+0

非常感謝你:)它的工作原理。我不知道我怎麼想不到這一點:P – davidaam 2012-07-10 00:33:37