简体   繁体   中英

Listing category and sub-categories in a HTML SELECT

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 "&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
           }

    }
}  

}

If you want to use optgroup try it:

// 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>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM