0

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

猫(分贝表)

cat_id | 猫名 | 猫父母 | 猫短
__________________________________________
1 | 主页 | 0 | 家
__________________________________________
2 | 游戏 | 1 | 游戏
__________________________________________
3 | 跳棋 | 2 | 跳棋

到目前为止,我构建的代码只允许菜单中有 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 轻松操作列表项元素来执行实际的下拉。

4

1 回答 1

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正确填充。

请注意,如果您的表变得太大,这将占用大量内存,但至少它只会访问数据库一次。

于 2012-11-22T17:38:08.533 回答