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

南楼画角 提交于 2019-12-11 22:29:58

问题


I wrote a dynamic menu based on three table on db which reflects below level frame:

> 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.


回答1:


Have a look at:

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. :)




回答2:


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)

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.



来源:https://stackoverflow.com/questions/5828960/building-unordered-list-navigation-menu-with-an-easier-way-code-beautifying-qu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!