根据PDO的fetchAll()
方法,我的数据库中有一个二维的城市阵列,我用它来生成一个带有选项的下拉列表,比如:
foreach($option as $city) {
echo '<option value="'. $city['city_id'] . '">' . $city['city_name'] . '</option>';
}
这一切都很好,但它返回了一个相当长的来自整个州/省的城市列表,因此为了使选择更友好,我想根据它们的起始字母动态添加类别<optgroup>
"部分"。结果已经按名称排序,因此该部分已得到处理。
我曾尝试使用preg_grep()
和preg_match()
将阵列拆分为更小的阵列,然后为每个阵列回显一个optgroup,但这并不完全奏效optgroup B在所有城市显示后被推到列表的底部。
$citiesA = preg_grep('/^A.*/', $option);
$citiesB = preg_grep('/^B.*/', $option);
echo '<optgroup label="A">';
foreach($citiesA as $a) {
echo '<option value="'. $a['city_id'] . '">' . $a['city_name'] . '</option>';
}
echo ' </optgroup>';
echo '<optgroup label="B">';
foreach($citiesB as $b) {
echo '<option value="'. $b['city_id'] . '">' . $b['city_name'] . '</option>';
}
echo ' </optgroup>';
任何关于如何实现这一目标的建议都将不胜感激。
怎么样
$startl=""; // current Starting letter
foreach($option as $o)
{
if (($c=substr($o['city_name'], 0, 1)) != $startl) // if starting letter changed
{
if ($startl) echo '</optgroup>';
echo '<optgroup label="'. $c .'">'; // create new group
$startl=$c;
}
echo '<option value="'. $o['city_id'] . '">' . $o['city_name'] . '</option>';
}
echo '</optgroup>'; // end the last group