Reputation: 91
I'm trying to generate optgroups and options with PHP from an array, and it generates it, but my optgroup is wrong. It display only the first word. In the page source it's correct.
$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>
.......
but on my select box I see only "first", instead of "first optgroup"
Any ideas?? Thanks!!
Upvotes: 0
Views: 713
Reputation: 418
try this,
$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>";
Upvotes: 1
Reputation: 360602
You'd need to embed some quotes:
echo "<optgroup label=\"{$optgroup}\">";
^^-----------^^----
Note the backslash escapes on the embedded quotes. This'll generate
<optgroup label="foo bar">
instead of the
<optgroup label=foo bar>
^^^--- value for "label" attribute
^^^---unknown random attribute
you're doing now
Upvotes: 1