如何从 PHP 数组中填充列表框/下拉框/选择框

2021-12-28 00:00:00 arrays drop-down-menu php

我需要编写自定义数组或 JSON 来填充列表框/下拉框/选择框并添加属性 selected="selected".

I need write a custom array or JSON to populate a Listbox/dropdown box/select box and add an attribute selected="selected".

例如:

<select id="test1" name="selectB" class="Field">
<option value="NO" selected="selected">No (Recommended)</option>
<option value="YES">Yes</option>
</select>

我不知道该怎么做.

推荐答案

<?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 数组的等价物是:

json equivalent of the array is:

[{"value":"1","label":"No (Recommended)","selected":true},{"value":"2","label":"Yes","selected":false}]

这是json_enconde($array);

相关文章