I have a category table that allows products to be nested to 5 levels deep.

I am trying to build a navigational menu using nested lists to represent the hierarchy of the categories.

The problem I am having is that if a parent category has more than 1 child category, the parent category appears more than 1 time in my list.


Here's what I'm outputting:
  • Annuals
    • Angelonia
  • Annuals
    • Bacopa
  • Annuals
    • Begonia
  • Ferns
  • Furniture
    • Beach House and Coastal Cottage Furniture
  • Seeds
    • Flower Seeds
  • Seeds
    • Organic Seeds



Here's what I want to output:
  • Annuals
    • Angeloni
    • Bacopa
    • Begonia
  • Ferns
  • Furniture
    • Beach House and Coastal Cottage Furniture
  • Seeds
    • Flower Seeds
    • Organic Seeds


Additionally, like I said, categories can be nested to 5 levels.

So how can I make it so that the hierarchy is correct WITHOUT repeating categories?

Here's what I have so far:


PHP Code:
$sql "
SELECT 
    L1.category_name AS L1name, 
    L2.category_name AS L2name, 
    L3.category_name AS L3name, 
    L4.category_name AS L4name, 
    L5.category_name AS L5name
FROM 
    default_categories L1
LEFT OUTER JOIN default_categories L2 ON L1.category_id = L2.category_parent      
LEFT OUTER JOIN default_categories L3 ON L2.category_id = L3.category_parent      
LEFT OUTER JOIN default_categories L4 ON L3.category_id = L4.category_parent      
LEFT OUTER JOIN default_categories L5 ON L4.category_id = L5.category_parent      
WHERE L1.category_parent = ''"
;

$list '<ul>';
while (
$row mysql_fetch_array($result)){
     
$list .= '<li>' $row['L1name'];
     
     if (
$row['L2name']) {
          
$list .= '<ul>';
         
$list .= '<li>' $row['L2name'];
         
         if (
$row['L3name']) {
            
$list .= '<ul>';
            
$list .= '<li>' $row['L3name'];
            
            if (
$row['L4name']) {
                
$list .= '<ul>';
                
$list .= '<li>' $row['L4name'];
                
                if (
$row['L5name']) {
                    
$list .= '<ul>';
                    
$list .= '<li>' $row['L5name'] . '</li>';
                } else {
                    
$list .= '</li></ul>';
                }
                
            } else {
                
$list .= '</li></ul>';
            }
            
        } else {
            
$list .= '</li></ul>';
        }
        
    } else {
        
$list .= '</li>';
    }    

}
$list .= '</ul>';
echo 
$list