简体   繁体   English

用更简单的方法构建无序列表导航菜单 - 代码美化问题

[英]Building unordered list navigation menu with an easier way - Code Beautifying Question

I wrote a dynamic menu based on three table on db which reflects below level frame:我基于 db 上的三个表编写了一个动态菜单,它反映了以下级别框架:

> Section
>> Categories
>>> Subcategory

Here is my code:这是我的代码:

include("connDB.php");

echo '<ul>';
$q1 = mysql_query("SELECT * FROM section ORDER BY section_name ASC");

while($getSection = mysql_fetch_array($q1)) {
    echo "<li><a href='content.php?sec={$getSection['section_id']}&cat='>{$getSection['section_name']}</a>";

    $q2 = mysql_query("SELECT * FROM category WHERE section_id = '{$getSection['section_id']}'");
    if(mysql_num_rows($q2) > 0) {
        echo "<ul>";
        while($getCat = mysql_fetch_array($q2)) {
            echo "<li><a href='content.php?sec={$getSection['section_id']}&cat={$getCat['category_id']}&scat='>{$getCat['category_name']}</a>";

            $q3 = mysql_query("SELECT * FROM subcategory WHERE category_id = '{$getCat['category_id']}'");
            if(mysql_num_rows($q3) > 0) {
                echo "<ul>";
                while($getSubCat = mysql_fetch_array($q3)) {
                    echo "<li><a href='content.php?sec={$getSection['section_id']}&cat={$getCat['category_id']}&scat={$getSubCat['subcategory_id']}&getDetail='>{$getSubCat['subcategory_name']}</a></li>";
                }
                echo "</ul>";
                echo "</li>";
            }
        }
        echo "</ul>";
        echo "</li>";
    }
}
echo '</ul>';

I am wondering if I can find any help to beautify this basic-level code to a better way, more professional way?我想知道是否可以找到任何帮助来美化这个基本级别的代码,以更好的方式,更专业的方式? Thanks for help.感谢帮助。

So I know this is an old question.所以我知道这是一个老问题。 However, for anyone who stumbles upon this there is a solution.但是,对于偶然发现此问题的任何人,都有一个解决方案。 It's identical to the other answer however it's also sometimes referred to as Modified Preordered Tree Traversal (MPTT)它与其他答案相同,但有时也称为修改的预排序树遍历 (MPTT)

Some web frameworks, like CakePHP and Django, have it built in and refer to it as a "Tree" it would greatly increase the flexibility of your menu as well as preserve order.一些 web 框架,如CakePHP和 Django,将其内置并将其称为“树”,这将大大增加菜单的灵活性并保留顺序。

Have a look at:看一下:

http://en.wikipedia.org/wiki/Nested_set_model http://en.wikipedia.org/wiki/Nested_set_model

remodel your three tables to just one, then change the recurisve calling to one sql statement, and do a little php-looping to create the list.将您的三个表改造成一个,然后将递归调用更改为一个 sql 语句,并执行一些 php 循环来创建列表。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM