2013-08-03 29 views
1

我試圖用來自數據庫的行做菜單,我一直在這裏閱讀關於做一個遞歸函數來評估parentId和Id和構建較低級別的選項,但在這裏沒有運氣。也試圖將SQL答案轉換爲一個多維數組,沒有運氣......php pdo導航菜單的遞歸函數

基本上我需要的是根據父級構建列表元素的集合,例如Dashboard.php是son.php的父級

這裏是我的代碼:

function buildMenu($userType){ 

    try{ 

     $db = new db(); 
     $conn = $db->conn(); 

     $SQL_BUILD_MENU = "select usertypes.id as menuId, 
     menu.name as menuName, menu.link as menuLink, 
     usertype_menu.parent_id as 
     parent from usertypes inner join usertype_menu on usertypes.id =        usertype_menu.usertype_id inner join 
     menu on usertype_menu.menu_id = 
     menu.id where usertypes.name='".$userType."'"; 

     $conn->prepare($SQL_BUILD_MENU); 
     foreach($check = $conn->query($SQL_BUILD_MENU) as $row) { 
       echo "<ul>"; 
       echo "<a href=".$row['menuLink']."><li>" . $row['menuName'] . "</li></a>"; 
       echo "</ul>";   
     } 

    } 

    catch(Exception $e){ 

     echo "Se ha presentado un error en buildMenu".$e; 

     } 


    } 

} 


+----+--------+-------------+-----------------+--------+ 
| id | menuId | menuName | menuLink  | parent | 
+----+--------+-------------+-----------------+--------+ 
| 1 |  1 | Dashboard | dashboard.php | 0  | 
| 2 |  1 | Interaction | interaction.php | 0  | 
| 3 |  1 | Son   | Son.php   | 1  | 
+----+--------+-------------+-----------------+--------+ 

在此先感謝。

回答

0

首先,清理您的查詢。使用準備好的語句並綁定參數,不要添加字符串。其次,一次獲取所有相關數據並從中構建一個數據結構。遞歸不是這裏的答案。

第三,無序列表不能有兒童。你需要將它們封裝在LI節點中。

<ul> 
    <li>Example 1</li> 
    <li>Example 2</li> 
    <li> 
    Example 3 with a child list 
    <ul> 
     <li>Example 3 Child 1</li> 
    </ul> 
    </li> 
</ul> 
  • 實施例1
  • 實施例2
  • 實施例3與子列表
    • 實施例3兒童1