I’m not really experienced in PHP JSON queries, I’m curious if someone could help me with it.
I’m trying to make a foreach call for every color in the JSON array (seen below).
something like this
foreach($json->data->colors as $color){ echo '<option value="'.$color.'">'.$color.'</option>'; }
JSON File
{ "data": { "colors": [ "Red", "Blue", "Green", "Yellow", "Pink" ], "Shapes": [ "Square", "Rectangle", "Circle", "Triangle" ] } }
Any help would be greatly appriciated!
Advertisement
Answer
If you’re looking to parse the JSON data, use json_decode()
on your JSON string. And then loop through the parsed JSON variable like you’re doing.
Complete code:
<?php $jsonString = '{ "data": { "colors": [ "Red", "Blue", "Green", "Yellow", "Pink" ], "Shapes": [ "Square", "Rectangle", "Circle", "Triangle" ] } }'; $json = json_decode($jsonString); echo '<select type="select" name="select">'; foreach($json->data->colors as $color){ echo '<option value="'.$color.'">'.$color.'</option>'; } echo '</select>'; ?>