2011-03-09 123 views
0

我需要編寫自定義數組或JSON來填充Listbox /下拉框/選擇框並添加屬性selected="selected"如何從PHP數組中填充Listbox /下拉框/選擇框

例如:

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

我無法弄清楚如何做到這一點。

+0

輸出能不能解釋一下?你的數據來自哪裏?你想讓PHP獲取數據庫查詢的結果,並創建一個選擇? – David 2011-03-09 17:47:48

+0

這個非常類似的問題剛剛發佈:http://stackoverflow.com/questions/5249825/auto-populate-a-select-box-using-an-array-in-php – Nick 2011-03-09 17:48:02

回答

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);

+0

+1我喜歡你如何調整你的答案在http://stackoverflow.com/questions/5249825/auto-populate-a-select-box-using-an-array-in-php。 :) – Nick 2011-03-09 17:54:23

+0

赫赫感謝,非常類似的情況(: – amosrivera 2011-03-09 17:56:08

+0

@尼克:是的,如果我沒有達到每日投票限制,我肯定也會給+1 +1) – kapa 2011-03-09 17:56:38