2012-10-18 79 views
0

我有一個使用PHP生成的HTML來創建jQuery下拉菜單的菜單。用於構建菜單的信息從分類數據庫表來:php,jquery三級下拉菜單

貓(db表)

 
cat_id | cat_name | cat_parent | cat_short 
__________________________________________ 
1  | Home  | 0   | home 
__________________________________________ 
2  | Games | 1   | games 
__________________________________________ 
3  | Checkers | 2   | checkers 

,我已經建立了到目前爲止的代碼只允許在菜單2級水平,

<ul class="dropdown"> 
    <?php 
    $sql ='SELECT * FROM cats WHERE cat_parent = 0'; 
    $result = $db->sql_query($sql); 
    while($row = $db->sql_fetchrow($result)){ 
     $cats[] = array(
      'id' => $row['cat_id'], 
      'name' => $row['cat_name'], 
      'parent' => $row['cat_parent'], 
      'short' => $row['cat_short'], 
      'subs' => array() 
     ); 
    } 

    foreach($cats as $cat){ 
     $sql = 'SELECT * FROM cats WHERE cat_parent = '.$cat['id']; 
     $result = $db->sql_query($sql); 
     while($row = $db->sql_fetchrow($result)){ 
      $cat['subs'][] = array(
       'id' => $row['cat_id'], 
       'name' => $row['cat_name'], 
       'parent' => $row['cat_parent'], 
       'short' => $row['cat_short'] 
      ); 
     } 
     $menu[] = $cat; 
    } 

    foreach($menu as $cat){ ?> 
     <li class="ui-state-default"><a class="transition" href="index.php?mode=<?php echo $cat['short']; ?>"><?php echo $cat['name']; ?></a> 
     <?php if($cat['subs'] != '0'){ ?> 
      <ul class="sub_menu"> 
      <?php foreach($cat['subs'] as $sub){ ?> 
       <li class="ui-state-default"><a class="transition" href="index.php?mode=<?php echo $sub['short']; ?>"><?php echo $sub['name']; ?></a></li> 
      <?php } ?> 
      </ul> 
     <?php } ?> 
     </li> 
    <?php } ?> 
</ul> 

我怎麼能改寫這個(或寫一個函數),以能夠利用3層:不會爲第三級(即跳棋)添加另一個下拉列表?我只需要PHP循環,因爲我可以使用jquery輕鬆操作列表項元素來執行實際的下拉菜單。

+0

我用MYSQL重寫了這個問題。我的猜測是你可以改變你的查詢,返回一個已經完整嵌套的完整對象。我不是MYSQL的專業人士,但也許別人能夠提供幫助。 –

+0

@ComputerArts啊,是的。我沒有想過重構MySQL查詢本身的可能性。但是,我仍然不確定實現預期目標的正確語法。 – chaoskreator

回答

0

下面的代碼(未經測試,抱歉)可以做的伎倆用於任何數目的層次:

<?php 
# a key-value list of all cats by their IDs: 
$all_cats = array(); 

# the final list of cats we want: 
$cats = array(); 

$sql ='SELECT * FROM cats'; 
$result = $db->sql_query($sql); 

# fetch all cats 
while($row = $db->sql_fetchrow($result)){ 
    $all_cats[$row['cat_id']] = array(
     'id' => $row['cat_id'], 
     'name' => $row['cat_name'], 
     'parent' => $row['cat_parent'], 
     'short' => $row['cat_short'], 
     'subs' => array() 
    ); 
} 

# group cats by parent (note reference & to $cat) - we are dealing with the same object 
foreach ($all_cats as $id => &$cat) { 
    $parent = $cat['cat_parent']; 
    if ($parent == 0) { 
     $cats[] = $cat; 
    } else { 
     $all_cats[$parent]['subs'][] = $cat; 
    } 
} 

在結束時,$cats將包含第一級貓陣列,其subs填充正常。

請注意,如果您的表格變得太大,這將佔用大量內存,但至少它只會觸及數據庫一次。