Drop Down Option Groups from Multiple PHP Arrays
I have a quick question, and hopefully this is an easy one to answer:
I currently have the following PHP code (which works fine):
<?
$teams = array ('Team 1' => 'T1', 'Team 2' => 'T2', 'Team 3' => 'T3');
foreach ($teams as $team_name => $team_code) {
if ($row['db_code'] == $team_code) { // This is from a MySQL query
echo "<option value=\"$team_code\" selected>$team_name</option>";
}
else {
echo "<option value=\"$team_code\">$team_name</option>";
}
}
?>
How can I add an additional array into my foreach
statement, and then divy up into <optgroups>
?
$colors = array('Color 1' => 'C1', 'Color 2' => 'C2', 'Color 3' => 'C3');
This way, it would show up l开发者_运维问答ike this in the HTML:
<select id="some_id">
<optgroup label="Teams">
<option value="T1">Team 1</option>
<option value="T2">Team 2</option>
<option value="T3">Team 3</option>
<optgroup label="Colors">
<option value="C1">Color 1</option>
<option value="C2">Color 2</option>
<option value="C3">Color 3</option>
</select>
This would probably work, haven't tested it!
$teams = array ('Team 1' => 'T1', 'Team 2' => 'T2', 'Team 3' => 'T3');
$colors = array('Color 1' => 'C1', 'Color 2' => 'C2', 'Color 3' => 'C3');
$array = array('Teams' => $teams, 'Colors' => $colors);
foreach ($array as $key => $val)
{
echo '<optgroup label="'.$key.'">';
foreach ($val as $k => $v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
echo '</optgroup>';
}
You could change your structure a little bit:
$drop_down_options = array(
'Teams' => array(
"Team 1" => "T1",
"Team 2" => "T2",
"Team 3" => "T3"
),
'Colors' => array(
"Color 1" => "C1",
"Color 2" => "C2",
"Color 3" => "C3"
)
);
Then do a foreach like this:
foreach($drop_down_options as $group_name => $group){
echo "<optgroup label=\"$group_name\">";
foreach($group as $value => $name){
echo "<option value=\"$value\" selected>$name</option>";
}
echo "</optgroup>";
}
foreach($drop_down_options as $group_name => $group){
echo "<optgroup label=\"$group_name\">";
foreach($group as $value => $name){
echo "<option value=\"$value\" selected>$name</option>";
}
echo "</optgroup>";
}
精彩评论