从MySQL数据库中列出PHP中的子类别

时间:2012-11-18 16:52:40

标签: php mysql categories

我一直致力于建立一个简单的电子商务系统的项目,该系统一直很好,直到我开始为类别显示导航。

当我在MySQL中构建类别时,我有类似的东西:

id             name             parent_id
1              books            null
2              art              1
3              biography        1
4              games            null
5              electronics      null
6              FPS              4

我编写了以下SQL来检索父类别,然后检索子类别:

SELECT parent.name AS parent_name, child1.name AS child1_name
FROM categories AS parent
LEFT OUTER JOIN categories AS child1 ON child1.parent_id = parent.id
WHERE parent.parent_id IS NULL
ORDER BY parent_name, child1_name

结果是一个包含多个数组的数组:

Array
(
    [0] => Array
    (
        [parent_name] => Books
        [child1_name] => Art
    )

    [1] => Array
    (
        [parent_name] => Books
        [child1_name] => Biography
    )

    [2] => Array
    (
        [parent_name] => Clothes, Shoes & Watches
        [child1_name] => 
    )

    [3] => Array
    (
        [parent_name] => Computers & Office
        [child1_name] => 
    )

    [4] => Array
    (
        [parent_name] => Electronics
        [child1_name] => 
    )
)

我无法将此信息显示为无序列表。期望的效果是这样的:

<ul>
    <li>Books
        <ul>
            <li>Art</li>
            <li>Biography</li>
        </ul>
    </li>
    <li>Computers</li>
    <li>Electronics</li>
</ul>

有没有人能解决这个问题?我是否需要更改MySQL代码甚至数据库结构?

提前致谢。

1 个答案:

答案 0 :(得分:3)

解决方案并不简单,但可以适用于你:)。

$newArray = array();
foreach($arrayFromDatabase as $key => $category){
   //replace key
   $newArray[$category['parent_name']][] = $category['child1_name'];   
}

//Open list
$toEcho = "<ul>";
foreach($newArray as $name => $subCat){
   if(!empty($subCat)){
     $toEcho_ = "<ul>";
     foreach($subCat as $cat){
        $toEcho_ .= "<li>$cat</li>";   
     }
     $toEcho_ .= "</ul>";
     $toEcho .= "<li>$name $toEcho_</li>"; 
   } else{
      $toEcho .= "<li>$name</li>";   
   } 
}

//Close list
echo $toEcho . "</ul>";