1

PHP新手在这里。我目前正在使用 PHP 开发一个购物车网站,我的问题是如何在我的侧边栏上制作动态类别树列表?因为我不知道如何实现它。我已完成在数据库中添加类别。

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,你应该在路上,这些链接需要改变以适应你的网站,它们只是一个例子

于 2011-07-31T13:06:06.870 回答