php – 选择字段的optgroup – 同一个表中的组和选项字段.我怎样才能做到这一点?

我有一个搜索表单,用于搜索数据库中的表.该表包含以下列:

icao – 名字 – 国家

我有PHP将这些字段放在每行的选择选项中使用以下查询

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

        return DB::get_results($query);
    }

那么PHP如下:

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

这项工作正常,但我希望能够将国家/地区列用作选项组,因此每个国家/地区都是一个选项组,其中该国家/地区的相应机场位于右侧optgroup中.

我试过这个:

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

但它只是为每个机场创建了一个optgroup.

对此有任何帮助非常感谢,并提前感谢.

斯图尔特

解决方法:

首先,修改查询以按国家/地区排序,然后依次为icao.

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

然后尝试这个:

$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>';
}

顺便说一句:为了避免代码中的XSS vulnerabilities,你真的应该包装你在htmlspecialchars()中构建的HTML的所有动态部分或类似的功能.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...