我有一个带有PHP'foreach'的下拉菜单,我循环填充选择选项 . 这很好用 . 但是,我想要做的是使用“optgroup”选项有各种子标签 . 在我返回的数组中,我有一个“蓝色”,“绿色”和“红色”的“类型” . 如何根据$ album ['type']将选择选项拆分为多个组?
这是我的代码:
$query = mysql_query("SELECT * FROM background_albums);
$albums = array();
while($row = mysql_fetch_assoc($query)) {
array_push($albums, $row);
}
<select name="backgroundList" id="backgroundList">
<? foreach($albums as $album) { ?>
<option value="<?=($row['id']);?>"><?=$row['title'];?></option>
<? } ?>
</select>
这是我想在foreach循环中实现的那种东西:
if ($album['type'] == 'green')...
<optgroup label="Green Backgrounds">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</optgroup>
if ($album['type'] == 'blue')...
<optgroup label="Blue Backgrounds">
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
</optgroup>
3 回答
尝试
检查类型是否从先前的值更改,然后发出相应的标记 .
按类型排序查询:
在网上搜索各种帖子之后...然后进行了大量的反复试验,我终于找到了一个非常有效的optgroup解决方案 .
这段代码与tagrin0非常相似,但我想我会提供一些更多的评论来帮助其他新手可能想要清楚地了解如何使这个工作没有太多的捏造和代码解释 .
希望它可以帮助某人 .
Here's the table structure...
opt_id | grp_id | optName | grpName | optAbbrv ...
//结束php