在 HTML SELECT 中列出类别和子类别

use*_*831 5 html php

我想在选择列表(下拉列表)中显示类别和子类别,如下图所示。

在此输入图像描述

这是我在 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>';
Run Code Online (Sandbox Code Playgroud)

此代码在下拉列表中显示我的所有类别。但我需要为我的子类别添加一些缩进。

任何人都可以告诉如何去做。

谢谢。

CDr*_*sos 2

尝试添加"&nbsp;"子类别,这是根据需要添加任意多个空格的 HTML 方式

函数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
           }

    }
}  
Run Code Online (Sandbox Code Playgroud)

}