如何将optgroup添加到下拉循环?

时间:2011-11-13 15:25:28

标签: php mysql select loops optgroup

我有一个循环,在下拉框中显示变量列表(基于过滤的类别)。我想从我的表中添加选项组(使用子类别)。如何将其添加到循环的一部分?

在下面的示例中,类别为“countries”,子类别为“continents”。我希望这些国家在相应的大陆optgroup中列出。

<select id="country">
  <option value="">Select</option>

 <?php
     $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                              FROM constants WHERE category='Countries'
                              ORDER BY display");
     while ($row = $c_sth->fetch ()) {
       echo '<option value="'.$row['value'].'">'.$row['display'].</option>'."\n";
     }
 ?>

</select>

2 个答案:

答案 0 :(得分:4)

<?php
 $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                          FROM constants WHERE category='Countries'
                          ORDER BY subcategory, display"); # group by category first
 $current_subcategory = "";
 while ($row = $c_sth->fetch ()) {
   if ($row["subcategory"] != $current_subcategory) { # if category has changed
       if ($current_subcategory != "") { # if there was already a category active
           echo "</optgroup>"; # close it
       }
       echo '<optgroup label="'.$row['subcategory'].'">'; # open a new group
       $current_subcategory = $row['subcategory'];
   }
   echo '<option value="'.$row['value'].'">'.$row['display'].</option>'."\n';
 }
 echo "</optgroup>"; # close the final group
?>

答案 1 :(得分:1)

<select id="country">
  <option value="">Select</option>

 <?php
     $c_sth = $c_dbh->query ("SELECT category, subcategory, display, value
                              FROM constants WHERE category='Countries'
                              ORDER BY subcategory, display");

     $lastgroup = "";
     while ($row = $c_sth->fetch ()) {
       if ($lastgroup != $row['subcategory']) 
         echo '<optgroup label="'.$row['subcategory'].'">\n';
       echo '<option value="'.$row['value'].'">'.$row['display'].'</option>\n';
       if ($lastgroup != $row['subcategory']) 
         echo '</optgroup>\n';
       $lastgroup = $row['subcategory'];
     }
 ?>

</select>