xonorageous
xonorageous

Reputation: 2281

Listing Categories then subcategories in PHP from MySQL database

I've been working on a project to build a simple ecommerce system that's been going fine until I started working on displaying the navigation for categories.

When I build the categories in MySQL I have something like:

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

I've written the following SQL to retrieve the parent categories then the child categories:

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

The result of this is an array containing multiple arrays :

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] => 
    )
)

I'm having trouble displaying this information as an unordered list. The desired effect would be something like this:

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

Does anybody have a solution for this problem? Do I need to change my MySQL code or even the database structure?

Thanks in advance.

Upvotes: 2

Views: 3669

Answers (1)

Richard Hutta
Richard Hutta

Reputation: 679

Solution isn't simple but can work for u :).

$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>";

Upvotes: 3

Related Questions