3

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

4 に答える 4

14

試す

<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>
于 2012-10-11T04:07:55.420 に答える
4

オンラインでさまざまな投稿を検索した後、試行錯誤を繰り返した結果、うまく機能するoptgroupソリューションを見つけました。

このコードはtagrin0とかなり似ていますが、コードをいじくり回したり解釈したりせずにこれを機能させる方法を明確に把握したい他の初心者を支援するために、もう少しコメントを付けたいと思いました。

それが誰かを助けることを願っています。

これがテーブルの構造です...

opt_id | grp_id | optName | grpName | 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を終了します

于 2014-02-07T13:35:11.883 に答える
2

タイプが前の値から変更されたかどうかを確認してから、適切なタグを発行します。

タイプ別にクエリを並べ替えます。

$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
于 2012-10-11T03:57:57.900 に答える
0

この方法では、配列を並べ替える必要はありません

<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>
于 2020-05-13T10:19:28.263 に答える