PHP to build Dropdown list from JSON

Viewed 26

I am looking for the advice,

The story is I would like to build a dropdown list based on below JSON

{"Name":["Anton","Joe","Andi","Susan","Alex"]}

I have tried to use below code, but doesn't work and blank, $result below is the above json name

<select id="name" name="name">
                        <option value="none"></option>
                        <?php
                         $DataObject = json_decode($result);
                          foreach($DataObject as $t) {
                            echo '<option value="'. $t['Name'].  '">'. $t['Name'].'</option>';      
                          }
                        ?>
                    </select>
1 Answers

Try this:

$opt = '<select>';
$jsn = '{"Name":["Anton","Joe","Andi","Susan","Alex"]}';
$data = json_decode($jsn, true);
foreach($data['Name'] as $key => $name){
  $opt .= "<option id=\"o$key\" value=\"$name\">$name</option>\n"; 
}
echo  "$opt</select>";

enter image description here

Related