我需要编写自定义数组或JSON来填充列表框/下拉框/选择框并添加属性selected="selected"
。
例如:
<select id="test1" name="selectB" class="Field">
<option value="NO" selected="selected">No (Recommended)</option>
<option value="YES">Yes</option>
</select>
我无法弄清楚如何做到这一点。
答案 0 :(得分:2)
<?php
$array = array(
array("value"=>"NO","label"=>"No (Recommended)","selected"=>true),
array("value"=>"YES","label"=>"Yes","selected"=>false),
);
?>
<select>
<?php foreach($array as $option) { ?>
<option value="<?php echo $option['value'] ?>" <?php if($option['selected']){ ?>selected="selected"<?php }?>>
<?php echo $option['label'] ?>
</option>
<?php }?>
</select>
json等效于数组:
[{"value":"1","label":"No (Recommended)","selected":true},{"value":"2","label":"Yes","selected":false}]
这是json_enconde($array);