选择嵌入了while循环的Optgroup组

时间:2014-02-28 11:26:59

标签: javascript php

我有一个while循环,它获取agentspec表中的所有值,并将它们设置为选择字段中的选项。

我在agentspec表格中的值按category字段分组,我想将category字段用作我的optgroup标签。

这是我尝试过的。它当前输出所有category字段值,后跟所有spec值 例如

Category: Farmer 
Category: Farmer
Category: Farmer
Category: Colour
Category: Colour
Spec: Grain
Spec: Sand
Spec: Fruit
Spec: Red
Spec: Blue

我希望它根据spec字段中设置的组输出category值。

例如

Category: Farmer 
Spec: Grain
Spec: Sand
Spec: Fruit
Category: Colour 
Spec: Red
Spec: Blue

代码:

$st = DBase::singleton()
            ->prepare(
                'select * ' .
                'from `agentspec` ' .
                'limit 0,30');

    $option = '';
    $optgroup = '';
    if ($st->execute())
    {
           while ($row = $st->fetch(PDO::FETCH_OBJ))
            {
    $id = $row->id;
    $cat = $row->category;
    $spec = htmlspecialchars($row->spec);
    $desc = htmlspecialchars($row->desc);

    $optgroup .=  '<optgroup label= '.$cat.'></optgroup>';
    $option .= '<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';

    }
    }


    ?>


    <select id="selectbox" name="" class=form-control>
    <option selected="selected">Select a Specialist Area
    </option>
    <?php echo $optgroup;?>
    <?php echo $option;?>

</select>

1 个答案:

答案 0 :(得分:1)

选项是optgroup的子元素,因此您必须执行类似的操作 这粗糙的fiddle example

您的代码段的重写版本:

<?php
        $st = DBase::singleton()
                    ->prepare(
                        'select * ' .
                        'from `agentspec` ' .
                        'limit 0,30');


        $optHtml= '';
        $optgroups = array();

        if ($st->execute())
        {
            while ($row = $st->fetch(PDO::FETCH_OBJ))
            {
                $id = $row->id;
                $cat = $row->category;
                $spec = htmlspecialchars($row->spec);
                $desc = htmlspecialchars($row->desc);
                if (!array_key_exists($cat, $optgroups)) {
                    $optgroups[$cat] = "";
                }
                $optgroups[$cat].='<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';
            }
            foreach($optgroups as $label=>$optionsHtml) {
                $optHtml.= '<optgroup label="'.$label.'">'.$optionsHtml.'</optgroup>';
            }   
        }


?>

<select id="selectbox" name="" class=form-control>
    <option selected="selected">Select a Specialist Area</option>
    <?php echo $optHtml; ?>
</select>