由php生成的optgroup

时间:2014-09-09 16:46:52

标签: php html optgroup

我尝试使用PHP从数组生成optgroups和选项,并生成它,但我的optgroup是错误的。它只显示第一个单词。在页面源中,它是正确的。

$my_array = array(
    first optgroup => array(
        key1 =>value1,
        key2 => value2,
        key3 => value3,
    ),
    second optgroup => array(
        key1 =>value1,
        key2 => value2,
        key3 => value3,
    ),
);
foreach ($my_array as $optgroup => $other_array) {
    echo "<optgroup label=". $optgroup . ">";

    foreach ($other_array as $key => $value) {
        echo "<option value=" . $key . ">" . $value . "</option>";
}
    echo "</optgroup>";

in the source code is fine:

<optgroup label=first optgroup>
    <option value=key1>value1</option>
    <option value=key2>value2</option> 
    .......

但在我的选择框中,我只看到&#34;第一个&#34;,而不是&#34;第一个optgroup&#34;

任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

您需要嵌入一些引号:

echo "<optgroup label=\"{$optgroup}\">";
                      ^^-----------^^----

请注意嵌入式引号上的反斜杠转义符。这将生成

<optgroup label="foo bar">

而不是

<optgroup label=foo bar> 
                ^^^--- value for "label" attribute
                    ^^^---unknown random attribute

你现在正在做什么

答案 1 :(得分:0)

试试这个,

$my_array = array(
    'first optgroup' => array(
        'key1' =>'value1',
        'key2' => 'value2',
        'key3' => 'value3',
    ),
    'second optgroup '=> array(
        'key1' =>'value1',
        'key2' => 'value2',
        'key3' => 'value3',
    ),
);

echo "<select>";
foreach ($my_array as $optgroup => $other_array) {
    echo "<optgroup label=". $optgroup . ">";
    foreach ($other_array as $key => $value) 
        echo "<option value=" . $key . ">" . $value . "</option>";
}
    echo "</optgroup>";
});
echo "</select>";