使用“optgroup"选项选择下拉 PHP foreach 循环 [英] Select Dropdown PHP foreach loop with 'optgroup' options

查看:34
本文介绍了使用“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 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆