optgroup用于选择字段 - 同一表中的组和选项字段。我怎样才能做到这一点?

问题描述:

我有一个搜索表单在我的数据库中搜索一个表。该表具有以下的列: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,因此每个国家是一个OPTGROUP,与各自的airpo在正确的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。

对此的任何帮助将非常感激,并提前感谢。

斯图尔特

首先,修改查询通过country第一,然后icao排序。 BTW

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

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

那就试试这个为避免你的代码XSS vulnerabilities,你真的应该换你正在构建中htmlspecialchars()的HTML或一些类似功能的所有动态部分。

+1

工作完美,非常感谢你! – 2011-06-13 05:25:08

+0

@Stuart Boardman:我的荣幸:) – Asaph 2011-06-13 05:26:16