我真的很想做这样的事情http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup 但我在数据库中有主类别和子类别,我真的不知道如何在一段时间内管理它。我怎样才能做到这一点 ?其实循环就是这样的,但是由于我的需要,我不能再使用它了
<select class="form-control" id="subcategory" name="subcategory" required>
<?php
$categories="SELECT Name,Category FROM SubCategory ORDER BY Category ASC, Name ASC;";
$query_categories=mysqli_query($connh,$categories);
while($rows_categories=mysqli_fetch_array($query_categories)){
echo'<option>'.$rows_categories['Category'].'/'.$rows_categories['Name'].'</option>';
}
?>
</select>
p.s:Category为主Category,Name为子Category
我想将主类别放入 <optgroup>
但由于一个类别包含多个子类别,我不知道如何放置<optgroup>
在某种程度上,它只显示主类别 1 次,而不是每条记录。
最佳答案
在你的情况下,如果当前主类别已添加到你的html上,如果我理解你的数据库中的字段,名称和类别有字符串值,你不需要两个查询或两个同时,但只检查变量,例如这个:
<select class="form-control" id="subcategory" name="subcategory" required>
<?php
$categories="SELECT Name,Category FROM SubCategory ORDER BY Category ASC, Name ASC;";
$query_categories=mysqli_query($connh,$categories);
$currentMainCategory = null;
while($rows_categories=mysqli_fetch_array($query_categories)){
// check if your current category was diferent of row category
if($currentMainCategory != $rows_categories['Category']) {
// check if is not null (for close </optgroup>)
if(!is_null($currentMainCategory)) {
echo '</optgroup>';
}
// set your new current category for this loop
$currentMainCategory = $rows_categories['Category'];
echo '<optgroup label="'. $rows_categories['Category'] .'">';
}
// do not forget put value of this category if you needed
echo'<option>' . $rows_categories['Name'] . '</option>';
}
// then check again for close last optgroup if is opened
if(!is_null($currentMainCategory)) {
echo '</optgroup>';
}
?>
</select>
关于php - 如何从数据库中放入 <select> 类别和子类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38075261/