[英]Listing category and sub-categories in a HTML SELECT
我想在选择列表(下拉列表)中显示类别和子类别,如下图所示。
这是我在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>';
此代码在我的下拉列表中显示所有类别。 但我需要在子类别中添加一些缩进。
任何人都可以告诉你该怎么做。
谢谢。
尝试添加" "
在子类别上,这是添加任意数量空格的HTML方式
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
}
}
}
}
如果你想使用optgroup试试:
// 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>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.