Chr*_*ris 2 php foreach select optgroup
我有一个带有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>
Run Code Online (Sandbox Code Playgroud)
这是我想在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>
Run Code Online (Sandbox Code Playgroud)
air*_*r4x 12
尝试
<select name="backgroundList" id="backgroundList">
<?php
$album_type = '';
foreach ($albums as $album) {
if ($album_type != $album['type']) {
if ($album_type != '') {
echo '</optgroup>';
}
echo '<optgroup label="'.ucfirst($album['type']).' Backgrounds">';
}
echo '<option value="'.$album['id'].'">'.htmlspecialchars($album['title']).'</option>';
$album_type = $album['type'];
}
if ($album_type != '') {
echo '</optgroup>';
}
?>
</select>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14664 次 |
最近记录: |