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

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.
Try adding " " 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 .= "  ";
       }
           echo "<option>".$space."$nm</option>\n";
           if (isset($cats[$id])) {
               displayList($cats, $id, $level+1);  //increment level
           }
    }
}  
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With