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.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能