douba1214 2011-06-13 04:53
浏览 82
已采纳

optgroup for select field - 同一个表中的group和option字段。 我怎样才能做到这一点?

I have a search form that searches a table in my database. The table has the following columns:

icao - name - country

I have the php that will place these fields in select options for each row with the following query:

 public function airportstuff() {
        $query = "SELECT icao, name, country
                FROM phpvms_airports
                ORDER BY icao";

        return DB::get_results($query);
    }

Then the php is as follows:

 <?php foreach ($airports as $airport)
 {echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';}
                    ?>

This works OK, but I want to be able to use the country column as an optgroup, so each country is an optgroup, with the respective airports for that country in the right optgroup.

I've tried this:

<?php
foreach ($airports as $airport)
{
echo '<optgroup label="'.$airport->country.'">';
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
?>
<?php echo '</optgroup>';}?>

But it just creates an optgroup for every airport.

Any help on this would very much be appreciated, and thanks in advance.

Stuart

  • 写回答

1条回答 默认 最新

  • douren5898 2011-06-13 05:12
    关注

    First of all, modify the query to sort by country first, then icao.

    public function airportstuff() {
        $query = "SELECT icao, name, country
                FROM phpvms_airports
                ORDER BY country, icao";
        return DB::get_results($query);
    }
    

    Then try this:

    $previousCountry = null;
    foreach ($airports as $airport) {
        if ($previousCountry != $airport->country) {
            // close the previous optgroup tag only if this isn't our first time through the loop
            if ($previousCountry !== null) {
                echo '</optgroup>';
            }
            echo '<optgroup label="'.$airport->country.'">';
        }
        echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
        $previousCountry = $airport->country;
    }
    // close the final optgroup only if we went through the loop at least once
    if ($previousCountry !== null) {
        echo '</optgroup>';
    }
    

    BTW: To avoid XSS vulnerabilities in your code, you really should wrap all dynamic parts of the HTML you're building in htmlspecialchars() or some similar function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题