Category and Subcategories in HTML SELECT

I want to display categories and subcategories in a select list (drop-down list) as shown below.

enter image description here

This is how I tried this 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 displays all my categories in my drop-down list. But I need to add some indentation to my subcategories.

Can anyone tell how to do this.

Thanks.

+4
source share
2 answers

Try adding "&nbsp;"in subcategories, this is the HTML way to add as many spaces as possible

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
           }

    }
}  

}

+2
source

If you want to use optgroup, try:

// 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) {

            if (isset($cats[$id])) {
                echo "<optgroup label='$nm'>";
                displayList($cats, $id, $level + 1);
                echo "</optgroup>";
            } else {
                echo "<option>$nm</option>";
            }
        }
    }
}

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

Source: https://habr.com/ru/post/1611157/


All Articles