php - 显示 oscommerce 中类别下的子类别

标签 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,子类别使用 parent_id 字段对它们所属的类别进行排序。有什么想法吗?

最佳答案

我不确定如何使用单个 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);
?>

关于php - 显示 oscommerce 中类别下的子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12583203/

相关文章:

php - 通过命令行运行 php 脚本时如何加载 Zend 类

php - SQL查询不同的表并显示所有

python - os.listdir 返回带有神秘字符的列表

C# 具有多个分支的链表

php - 如何将php数组保存到mysql表中?

php - SQL 查询 OR 和 AND

php - 当用户提交具有不同数据的表单时终止第一个查询

php - 使 MySQL 中的文件的 URL SEO 友好

php - SQL WHERE 查询仅适用于某些列

Python- For Loop - 增加列表中每个元组的每个索引位置