PHP: Dynamic Drop down with optgroup

匆匆过客 提交于 2019-11-28 11:28:35

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'];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!