PacPac PacPac - 3 months ago 12x
JSON Question

Build a select box from Json datas in PHP

How from this Json, I can build a select box with PHP ?

"1": "Item 1",
"2": "Item 2",
"3": "Item 3",
"4": "Item 4"

Like this:

<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>

Thanks for your help.


If you have your JSON stored as a string you should use json_decode to transform it into an array, and then itarate over the array. For example:

$myJson = "{'key':'value'}";
$myArray = json_decode($myJson);
$select = "<select>";

foreach($myArray as $key=>$val){
    $select .= "<option value='". $key."' >". $val."</option>";

$select .= "</select>";

echo $select;