php,jquery三级下拉菜单

时间:2012-10-18 00:14:43

标签: php jquery html mysql drop-down-menu

我有一个使用PHP生成的HTML创建jQuery下拉菜单的菜单。用于构建菜单的信息来自类别的数据库表:

cats(db table)

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

到目前为止,我构建的代码只允许菜单中的2个级别,并且不会为第3级添加另一个下拉列表(即Checkers):

<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轻松操作列表项元素来执行实际的下拉。

1 个答案:

答案 0 :(得分: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填充正确。

请注意,如果你的表太大,这将占用大量内存,但至少它只会打到数据库一次。