<?php
$options = array('volvo'=>'Volvo', 'saab' =>'Saab', 'audi' => 'Audi' );
echo "<select name='sss'>\n";
foreach ($options as $k=>$v) echo "<option value='$v' >$k</option>\n";
echo "</select>\n";
?>
问题:
如何将'audi'作为默认值而不是'volvo'?我知道我们可以在html中设置'selected',但是我怎么能在这个php脚本中做到这一点?
答案 0 :(得分:6)
您可以检测默认值是否是您想要的值并插入您已识别的HTML:
$defaultVal = 'Audi';
foreach ($options as $k=>$v) {
$selected = ($v == $defaultVal) ? " selected='selected'" : "";
echo "<option value='$v'$selected>$k</option>\n";
}
答案 1 :(得分:2)
我通常会创建一个辅助函数来输出选择
function showSelect($name, $options, $selected, $attr = array()){
$str = "<select name='".$name.'"';
foreach($attr as $name=>$val){
$str.= " ".$name."='".$val."'";
}
$str.=">";
foreach($options as $k=>$val){
$str.= "<option value='".$val."'".($val==$selected?" selected='selected'":"").">".$k.'</option>';
}
$str.="</select>";
return $str;
}
然后打电话
echo showSelect("sss", $options, "audi", array("id"=>"manufacturer"));
答案 2 :(得分:0)
Try this:
$options = array('volvo'=>'Volvo', 'saab' =>'Saab', 'audi' => 'Audi' );
$select_value = 'audi';
<select id="test" name="test">
<?php foreach($option as $row) {?>
<option value="<?php echo $row?>" <?php echo (strcmp($select_value,$row)==0) ?"selected='selected":'' ?>><?php echo $row?></option>
<?php } ?>
</select>