Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing category and sub-categories in a HTML SELECT

Tags:

html

php

I want to display categories and sub-categories in a select list (drop-down list) like the image below.

enter image description here

This is how I tried it in PHP:

// Fetch all the records:
while ($stmt->fetch()) {        
    $cats[$parent][$id] = $name;        
}

function displayList(&$cats, $parent, $level=0) {

    if ($parent==0) {
        foreach ($cats[$parent] as $id=>$nm) {
            displayList($cats, $id);
        }
    }
    else {
        foreach ($cats[$parent] as $id=>$nm) {
            echo "<option>$nm</option>\n";
            if (isset($cats[$id])) {
                displayList($cats, $id, $level+1);  //increment level
            }
        }
    }  
}

echo '<select>';
    displayList($cats, 0);
echo '</select>';

This code display all my categories in my dropdown list. But I need to add some indent to my sub categories.

Can anybody tell how to do it.

Thank you.

like image 809
user3733831 Avatar asked Sep 27 '22 12:09

user3733831


1 Answers

Try adding "&nbsp;" on subcategories, this is the HTML way to add as many spaces as you want

function displayList(&$cats, $parent, $level=0) {

if ($parent==0) {
    foreach ($cats[$parent] as $id=>$nm) {
        displayList($cats, $id);
    }
}
else {
    foreach ($cats[$parent] as $id=>$nm) {
       $space = "";
       foreach ($level){
           $space .= "&nbsp;&nbsp;";
       }
           echo "<option>".$space."$nm</option>\n";
           if (isset($cats[$id])) {
               displayList($cats, $id, $level+1);  //increment level
           }

    }
}  

}

like image 166
CDrosos Avatar answered Oct 13 '22 01:10

CDrosos