icao – 名字 – 国家
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.
对此有任何帮助非常感谢,并提前感谢.
斯图尔特
解决方法:
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的所有动态部分或类似的功能.