【问题标题】:Select Dropdown PHP foreach loop with 'optgroup' options使用“optgroup”选项选择下拉 PHP foreach 循环
【发布时间】:2012-10-11 03:52:04
【问题描述】:

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

这是我希望在 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>

【问题讨论】:

    标签: php select foreach optgroup


    【解决方案1】:

    试试

    <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>
    

    【讨论】:

    • 这个答案缺少教育解释。
    【解决方案2】:

    在网上搜索了大量不同的帖子之后……经过大量的试验和错误,我终于找到了一个效果很好的 optgroup 解决方案。

    这段代码与 tagrin0 非常相似,但我想我会为它提供更多的 cmets 来帮助其他可能想要清楚地了解如何使这项工作没有太多捏造和解释代码的新手.

    希望对某人有所帮助。

    这是表结构...

    opt_id | grp_id |选择名称 | grp名称 | optAbbrv...

    echo '<select id="xxx" class="xxx"> select">';
    echo '<option >Select an instance...</option>';
    
    $dbc = mysqli_connect('localhost','xxx','xxx','xxx') or die('Error connecting to MySQL server.');
    
    // run your query, something like
    // "SELECT <optgroup>_ID, <option>_ID, <optgroup>_Name, <ption>_Name FROM [mysql table this data is stored in] ORDER BY groupID, optionID"
    
    $select = "SELECT * FROM ci_opt ORDER BY grp_id, opt_id";
    
        $data  = @mysqli_query($dbc, $select) or die(mysql_error());
    
        // <optgroup> of the previous <option>
        $previous = "";
    
        // variable to set the first group
        $first_group = true;
    
        while($row = mysqli_fetch_array($data)) {
    
            // if this <option> changed <optgroup> from the previous one,
            // then add a new <optgroup>
            if ($row['grpName'] != $previous) {
                if (!$first_group) {
                    echo '</optgroup>';
                } else {
                    $first_group = false;
                }
                echo '<optgroup label="' . $row['grpName'] . '">';
                $previous = $row['grpName'];
            }
    
            // echo the current <option>
            // Note: I've also prepared the [onclick] for linking the select to an event
    
            echo '<option id="'. $row['optAbbrv'] .'" onclick="javascript:void()">' . ucwords($row['optName']) . '</option>';
    
        }
        // close the last <optgroup> tag
        echo '</optgroup>';
        // close the last <select> tag
        echo '</select>';
        // close the connection
        mysqli_close($dbc);
    

    //结束php

    【讨论】:

      【解决方案3】:

      检查类型是否从之前的值改变,然后发出适当的标签。

      按类型排序查询:

      $query = mysql_query("SELECT * FROM background_albums order by type"); //ordered query
      
      [...]
      
      $type = null;
      
      foreach ($albums as $album) {
        if ($album['type'] != $type) {  // type changed
          if ($type !== null) {
            echo '</optgroup>';  // close previous optgroup
          }
          $type = $album['type'];
          echo '<optgroup label="' . htmlspecialchars($type) . '">';  // start optgroup
        }
      
        [...]
      }
      
      echo '</optgroup>';  // close last optgroup
      

      【讨论】:

      • 为了使其正常工作,SELECT 应该具有“按类型排序”,对吗?
      【解决方案4】:

      此方法不需要对数组进行排序

      <select>
          <?php
          <!--  getting the groups to be one unique array -->
          $group= array_values(array_unique(array_column($album, 'type')));
                   for ($i=0; $i < count($group); $i++) : ?>
          <!--  for N group print  -->
          <optgroup label="<?=$album[$i];?>">
              <!-- loop trough the hole array to check if you belong to the group -->
              <?php foreach ($album as $value): ?>
              <!-- if you belong then we print -->
              <?php if ($group_level[$i]==$value['type']): ?>
              <option>
                  <?=$value['type'];?>
              </option>
              <?php endif ?>
              <?php endforeach ?>
          </optgroup>
          <?php endfor ?>
      </select>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多