PHP: Dynamic Drop down with optgroup

前端 未结 1 1164
遥遥无期
遥遥无期 2020-12-10 17:18

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         


        
相关标签:
1条回答
  • 2020-12-10 17:34

    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'];
    }
    
    0 讨论(0)
提交回复
热议问题