使用“optgroup"选项选择下拉 PHP foreach 循环

2021-12-26 00:00:00 select foreach php optgroup

我有一个带有 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>

相关文章