我有一个简单的问题,希望这很容易回答:
我目前有以下PHP代码(工作正常):
<?
$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>";
}
}
?>
如何在我的foreach
语句中添加其他数组,然后再分为<optgroups>
?
$colors = array('Color 1' => 'C1', 'Color 2' => 'C2', 'Color 3' => 'C3');
这样,它会在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>
答案 0 :(得分:0)
这可能有用,还没有测试过!
$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>';
}
答案 1 :(得分:0)
您可以稍微改变一下结构:
$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"
)
);
然后像这样做一个foreach:
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>";
}
答案 2 :(得分:0)
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>";
}