在php中,有没有更有效的方法来编写按状态分组的选择列表
我正在建立一个网站,它有一个按州分组的选择列表。有没有更有效的方法来编写这个选择列表,这样我就不会编写这么多不同的for循环了 我的数据库中有一个名为location的表:在php中,有没有更有效的方法来编写按状态分组的选择列表,php,database,select,drop-down-menu,Php,Database,Select,Drop Down Menu,我正在建立一个网站,它有一个按州分组的选择列表。有没有更有效的方法来编写这个选择列表,这样我就不会编写这么多不同的for循环了 我的数据库中有一个名为location的表: id region state 1 Sydney NSW 2 Newcastle NSW 3 Wollongong NSW 4 Wagga Wagga NSW 5 Geelong
id region state
1 Sydney NSW
2 Newcastle NSW
3 Wollongong NSW
4 Wagga Wagga NSW
5 Geelong Vic
…等等
目前,我正在按州分组的选择列表中打印它们,如下所示
<select name="location" id="location">
<?php
$locations = getTable("location", $DB);
$locationsByState = [];
//chunk array by state
foreach($locations as $loc)
{
$locationsByState[$loc['state']][] = $loc;
}
?>
<optgroup label="NSW">
<?php
foreach($locationsByState['NSW'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="QLD">
<?php
foreach($locationsByState['QLD'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="SA">
<?php
foreach($locationsByState['SA'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="VIC">
<?php
foreach($locationsByState['VIC'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="TAS">
<?php
foreach($locationsByState['TAS'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="WA">
<?php
foreach($locationsByState['WA'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="ACT">
<?php
foreach($locationsByState['ACT'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
<optgroup label="NT">
<?php
foreach($locationsByState['NT'] as $opt)
echo '<option>' . $opt['region'] .'</option>'
?>
</optgroup>
</select>
您可以在下面两个简单的循环中介绍这一点:
您可以在下面两个简单的循环中介绍这一点:
为什么不使用foreach
内部foreach
?为什么不使用foreach
内部foreach
?