1

根据 PDO 的fetchAll()方法,我有一个来自数据库的二维城市数组,用于生成带有选项的下拉列表,如下所示:

foreach($option as $city) {
    echo '<option value="'. $city['city_id'] . '">' . $city['city_name'] . '</option>';
}

这一切都很好,但是它返回了一个相当长的来自整个州/省的城市列表,因此为了使选择更友好一些,我想<optgroup>根据它们的起始字母动态添加分类“部分”。结果已经按名称排序,因此该部分已处理。

我尝试使用preg_grep()andpreg_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>';

非常感谢有关如何实现这一点的任何建议。

4

1 回答 1

2

怎么样

$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
于 2012-07-15T04:21:49.300 回答