Even if the table you mentioned does not contain the data required, there is a very basic principle of achieving what you want to achieve:
- Query all Rows that should form the
<options>
and add a second column, beeing the<optgroup>
.
like this:
Option 1 | Group 1
Option 2 | Group 1
Option 3 | Group 2
Option 4 | Group 3
- Iterate over all options, and whenever the group changes, print out an optgroup:
this one:
<?php
$data = array(array("option" => 1, "group" => "Group 1"),
array("option" => 2, "group" => "Group 1"),
array("option"=>3, "group" => "Group 2"));
$priorGroup = "";
echo "<select>";
foreach ($data AS $entry){
if ($entry["group"] != $priorGroup){ //Start new optgroup if group changed.
if ($priorGroup != ""){ //close prior optgroup if prior group WAS set.
echo "</optgroup>";
}
echo "<optgroup label='{$entry["group"]}'>";
}
echo "<option>{$entry["option"]}</option>"; //show option(s)
$priorGroup = $entry["group"]; //update priorGroup.
}
echo "</optgroup></select>"; //close last optgroup + select.
?>
Will output:
Group 1
1
2
Group 2
3
Your database query need to sort by group (and optional by option afterwards) otherwhise you might get something like this:
Group 1
1
Group 2
3
Group 1
2