选择下拉PHP foreach循环与“optgroup”选项 [英] Select Dropdown PHP foreach loop with 'optgroup' options
问题描述
我有一个PHPforeach下拉菜单,我循环填充选择选项。这很好。但是,我想要做的是使用optgroup选项的各种子标签。在我返回的数组中,我有一个蓝色,绿色和红色的类型。如何将选项分成基于$ album ['type']的组合?
这是我的代码: $ b $ ($ row = mysql_fetch_assoc)
$ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ($ query)){
array_push($ albums,$ row);
}
<?foreach($ albums as $ album){?>
< ;?}?>
< / select>
$ $ p
这是我想在foreach循环中实现的一种方式:
$ $ $ $ $ $ if($ album ['type'] =='green')...
< optgroup label =绿色背景>
< option> ;< / option>
< option> 2< / option>
< option> 3< / option>
< option> 4< ; / optgro
if($ album ['type'] =='blue')...
< optgroup label =Blue Backgrounds>
< option> 5< / option>
< option> 6< / option>
< option> 7< / option>
< option> 8< / option>
< / optgroup>
试试
< select name =backgroundListid =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>
I have a dropdown menu with a PHP 'foreach' that I loop through to populate the select options. This works well. However, what I'd like to do is have various sub labels using the "optgroup" option. In my returned array, I have a "type" of "blue", "green" and "red". How can I split the select options up into groups based on the $album['type']?
This is the code I have:
$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>
This is the kind of thing I'd like to achieve within the foreach loop:
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>
Try
<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>
这篇关于选择下拉PHP foreach循环与“optgroup”选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!