用PHP或JS从json文件中构建一个select


Build a select from a json file in PHP or JS

如何从这样的json文件中构建select?

{
    "AF": "Afghanistan",
    "AL": "Albania",
    "DZ": "Algeria",
    "AS": "American Samoa",
    ...
}

我正在尝试制作这样的东西:

<select>
  <option value="AF">Afghanistan</option>
  <option value="AL">Albania</option>
</select>

谢谢。

如果您使用Javascript,您应该使用Ajax来获取JSON数据。然后假设我们已经有了数据"JSON",您可以使用循环来处理它,例如:

var json_data = {
    "AF": "Afghanistan",
    "AL": "Albania",
    "DZ": "Algeria",
    "AS": "American Samoa"
};
var select = document.querySelector("#mySelect");
for(var countryCode in json_data){
   var option = new Option(json_data[countryCode], countryCode);
   select.appendChild(option);
}
<select id="mySelect"></select>

使用jQuery:

jQuery简化了您的工作,您有jQuery.getJSON()方法从文件中获取JSON数据,还有jQuery.each()方法用于处理对象

$.getJSON("https://raw.githubusercontent.com/tarraq/JSON-data-arrays/master/countries/english/countries-key-value.json", function(jsonData){
   var select = $("#mySelect");
   $.each(jsonData, function(key, country){
      select.append($("<option>", {value: key, text: country}))
   })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="mySelect"></select>

这将在PHP中发挥作用。获取JSON编码的字符串并将其转换为PHP数组。然后对数组进行迭代,使所有选项都选择。

<?php
$json = '{
    "AF": "Afghanistan",
    "AL": "Albania",
    "DZ": "Algeria",
    "AS": "American Samoa"
}';
$decoded = json_decode($json, true)
?>
</select>   
    <?  foreach($decoded as $key => $value){?>
        <option value="<? echo $key; ?>"><? echo $value; ?></option>
    <?  }   ?>
<select>
var myJason = {"AF": "Afghanistan","AL": "Albania","DZ": "Algeria","AS": "American Samoa"}

$.each(myJson,function(key,val) {
$('#mySelect').append('<option value="'+ key + '">' + val + '</option>');
});