I am developing a drop down menu that uses HTML optgroups for group names that employees are a part of. Here is the MySQL query and output:
mysql> SELECT employe
The two for loops are not nested in your code:
foreach ($groups as $label => $opt) { ?>
<optgroup label="<?php echo $label; ?>">
<?php } <-- wrong here
foreach ($groups[$label] as $id => $name) { ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
The result is that first all opt groups are created and then the employees for the last group are added (because $label
and $opt
are also available after the loop finished).
You have to nest the loops (using alternative syntax for control structures):
<?php foreach($groups as $label => $opt): ?>
<optgroup label="<?php echo $label; ?>">
<?php foreach ($opt as $id => $name): ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
Furthermore, I think you have to use the emp_id
, not the grp_id
when creating the array:
while ($qa = $employees->GetRows()) {
$groups[$qa['groupname']][$qa['emp_id']] = $qa['empname'];
}