douba1214
2011-06-13 04:53 阅读 60
已采纳

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

    点赞 10 评论 复制链接分享

相关推荐