我有一个 while 循环,用于获取 agentspec
表中的所有值并将它们设置为选择字段中的选项。
agentspec
表中的值按 category
字段分组,我想使用 category
字段作为我的 optgroup 标签。
这是我尝试过的。它当前输出所有 category
字段值,后跟所有 spec
值
例如。
Category: Farmer
Category: Farmer
Category: Farmer
Category: Colour
Category: Colour
Spec: Grain
Spec: Sand
Spec: Fruit
Spec: Red
Spec: Blue
我希望它根据在 category
字段中设置的组来输出 spec
值。
例如。
Category: Farmer
Spec: Grain
Spec: Sand
Spec: Fruit
Category: Colour
Spec: Red
Spec: Blue
代码:
$st = DBase::singleton()
->prepare(
'select * ' .
'from `agentspec` ' .
'limit 0,30');
$option = '';
$optgroup = '';
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$id = $row->id;
$cat = $row->category;
$spec = htmlspecialchars($row->spec);
$desc = htmlspecialchars($row->desc);
$optgroup .= '<optgroup label= '.$cat.'></optgroup>';
$option .= '<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';
}
}
?>
<select id="selectbox" name="" class=form-control>
<option selected="selected">Select a Specialist Area
</option>
<?php echo $optgroup;?>
<?php echo $option;?>
</select>
最佳答案
选项是 optgroup 的子元素,因此您必须执行类似的操作 这个粗fiddle example :
您的代码片段的重写版本:
<?php
$st = DBase::singleton()
->prepare(
'select * ' .
'from `agentspec` ' .
'limit 0,30');
$optHtml= '';
$optgroups = array();
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$id = $row->id;
$cat = $row->category;
$spec = htmlspecialchars($row->spec);
$desc = htmlspecialchars($row->desc);
if (!array_key_exists($cat, $optgroups)) {
$optgroups[$cat] = "";
}
$optgroups[$cat].='<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';
}
foreach($optgroups as $label=>$optionsHtml) {
$optHtml.= '<optgroup label="'.$label.'">'.$optionsHtml.'</optgroup>';
}
}
?>
<select id="selectbox" name="" class=form-control>
<option selected="selected">Select a Specialist Area</option>
<?php echo $optHtml; ?>
</select>
关于javascript - 在 while 循环中嵌入 Optgroup 的选择组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22093883/