开发者

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:

> 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开发者_如何学Go = '{$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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜