在oscommerce中的类别下显示子类别

时间:2012-09-25 12:42:58

标签: php mysql list categories

这是我到目前为止的标记:

<?php

$categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.categories_image, c.parent_id, c.sort_order, c.date_added, c.last_modified from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id order by c.sort_order ASC");
while ($categories = tep_db_fetch_array($categories_query)){

echo '<tr class="dataTableRow">
<td class="dataTableContent">' . $categories ['categories_name'] . '</td>';
?>

<td class="dataTableContent"></td>

<?php
echo '</tr>';
}
?>

这会在页面上显示所有类别和子类别,但是没有顺序,我需要的是子类别显示在主要类别下。我有一些线索,我将如何做到这一点,sort_order字段和parent_id字段之间的链接。主要类别使用sort_order字段作为id,而subccat使用parent_id字段对其所属的类别进行排序。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我不确定如何使用单个MySQL查询显示类别树,所以我建议使用递归PHP函数:

<?php
    function showChildCategories($parent) {
       $parent = intval($parent);

       // Select only categories with parent_id = $parent
       $categories_query = tep_db_query("select 
               cd.categories_name,
               c.categories_id
           from " . TABLE_CATEGORIES . " c, " . 
               TABLE_CATEGORIES_DESCRIPTION . " cd 
           where c.categories_id = cd.categories_id 
                 and c.parent_id = $parent
           order by c.sort_order ASC");

       // Go through all query result rows
       while ($categories = tep_db_fetch_array($categories_query)){
           // Show category name
           echo '<tr class="dataTableRow"><td class="dataTableContent">' . 
               $categories ['categories_name'] . '</td></tr>';

           // Show child categories for current row
           showChildCategories($categories ['categories_id']);
       } // while
    } // function showChildCategories

    // Show top-level categories and all their children recursively
    showChildCategories(0);
?>