本文介紹了使用“optgroup"選項選擇下拉 PHP foreach 循環的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個帶有 PHP 'foreach' 的下拉菜單,我循環遍歷它以填充選擇選項.這很好用.但是,我想要做的是使用optgroup"選項擁有各種子標簽.在我返回的數組中,我有一個藍色"、綠色"和紅色"的類型".如何根據 $album['type'] 將選擇選項分組?
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']?
這是我的代碼:
$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 循環中實現的那種:
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>
推薦答案
嘗試
<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>
這篇關于使用“optgroup"選項選擇下拉 PHP foreach 循環的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!