Per PDO's fetchAll()
method, I have a two-dimensional array of cities from my database which I use to generate a dropdown with options, like so:
foreach($option as $city) {
echo '<option value="'. $city['city_id'] . '">' . $city['city_name'] . '</option>';
}
This is all well and good, but it returns a rather long list of cities from an entire state/province, and so to make selection a little friendlier, I would like to dynamically add categorical <optgroup>
"sections" based on their starting letter. The results are already sorted by name, so that part's taken care of.
I've tried using preg_grep()
and preg_match()
to split the array up into smaller arrays and then echo out an optgroup for each of those, but that doesn't quite work... optgroup B gets shoved to the bottom of the list after all cities are displayed.
$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>';
Any suggestions on how to make this happen are much appreciated.
How about
$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