1

PHP初心者です。現在、PHP を使用してショッピング カート Web サイトを開発しています。質問は、サイド バーに動的なカテゴリ ツリー リストを作成する方法です。実装方法がわからないからです。データベースにカテゴリを追加しました。

4

1 に答える 1

1

必要なカテゴリのレベル数について提供した限られた情報で、ここに役立つ例がありますか?

    // create a function to get the categories
    function getCategories() {
        // query the top level categories
        $query = "SELECT catId,catName FROM categories ORDER BY catName";
        $result = mysql_query($query);
        // check that you got some results before proceeding
        if (mysql_num_rows($result)>0) {
            // create a $html variable to return from the function
            $html = '<ul class="L1-categories">';
            // loop through the results
            while ($rows = mysql_fetch_object($result)) {
                // append top level cats to your $html variable
                $html .= '<li><a href="index.php?category='.$rows->catId.'">'.$rows->catName.'</a>';
                // repeat the above query for 2nd level categories (sub cats)
                $queryL2 = "SELECT subId,subName FROM subCategories WHERE catId=".$rows->catId." ORDER BY subName";
                $resultL2 = mysql_query($queryL2);
                // check you got results
                if (mysql_num_rows($resultL2)>0) {
                    // continue appending the variable with some html that show sub cats indented
                    $html .= '<ul class="L2-categories">';
                    // loop through the sub cats
                    while ($rowsL2 = mysql_fetch_object($resultL2)) {
                        // if there were sub sub cats etc you just keep this code going deeper
                        $html .= '<li><a href="index.php?category='.$rows->catId.'&sub='.$rowsL2->subId.'">'.$rowsL2->subName.'</a></li>';
                    } // end sub cats loop
                    $html .= '</ul>';
                } // end check for results
                $html .= '</li>';
            } // end top level cats loop
            $html .= '</ul>';
        }
        return $html;
    }

    // usage
    echo getCategories();

サイドバーの必要に応じて、cssファイルのL1-categoriesとL2-categoriesをスタイルアップします。途中である必要があります。これらのリンクは、例としてそこにあるWebサイトに合わせて変更する必要があります。

于 2011-07-31T13:06:06.870 に答える