带有Optgroups的PHP mySQL选择框

I have a table with a list of "codes" and "groups". I need to be able to dynamically create a select box with the "codes" grouped using optgroup. I have tried messing with some solutions online but no luck.

TABLE INFO:

 CREATE TABLE `dtcodes` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `groups` varchar(30) NOT NULL,
 `code` varchar(5) NOT NULL,
 `name` varchar(40) NOT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=latin1

groups|codes|name
-----------------------
Materials|M1|No Product
Materials|M2|Low Brix
Other Equipment|AV1|Test1
Other Equipment|AV2|Test2

The PHP mysqli:

    $sqlcodes = "SELECT * FROM dtcodes ORDER BY groups ASC";
    $resultcodes = mysqli_query($con, $sqlcodes);

My goal at the end would be something like this.

 <select>
     <optgroup label="Materials">
         <option value="M1">No Product</option>
         <option value="M2">Low Brix</option>
     </optgroup>
     <optgroup label="Other Equipment">
         <option value="AV1">Test1</option>
         <option value="AV2">Test2</option>
     </optgroup>

Should have waited 20 minutes before posting this figured it out.

echo "<td><select class='form-control'>";
echo "<option>Select a code...</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
     $group[$row['groups']][] = $row;
}
 foreach ($group as $key => $values){
     echo '<optgroup label="'.$key.'">';
     foreach ($values as $value) 
     {
         echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
     }
     echo '</optgroup>';
 }
} else {}
echo "</select></td>";