I want to print the colonies array in a select by means of a foreach but it doesn't fit me.
{
"delegacion":"\u00c1lvaro Obreg\u00f3n",
"estado":"Ciudad de M\u00e9xico",
"region":"Centro",
"colonias":[
{"idcp":"27886","asentamiento":"Ampliaci\u00f3n El Capul\u00edn"},
{"idcp":"27887","asentamiento":"Liberales de 1857"},
{"idcp":"27888","asentamiento":"Bel\u00e9m de las Flores"},
{"idcp":"27889","asentamiento":"El Capul\u00edn"}
]
}
I managed to do it with jQuery in the following way but they ask me for it in PHP.
for (var i = 0; i < data.colonias.length; i++) {
$('#colonias').append('<option value="' + data.colonias[i].idcp + '">' + data.colonias[i].asentamiento + '</option>');
}
You can use
json_decode
to create an array or stdClass object from your json.Reading, in case of use
json_decode
creating a stdClass would be very simple.Looking at your code, it sounds like you'd want options with the colonies in the JSON.
To get it you can do:
Result:
Old answer with more explanations...
Here the
print_r($myJson);
is only informative, to see what is created.You will see this on the screen:
Result:
What matters is this. The end result would be something like this:
If you want you can put more information to give you a more exact answer, but roughly it would be something like this:
Where $data is the variable that contains the information of your query to the DB.
It is not very clear to me, but if it is from a json (it is what you have there) the ideal is with the each of jquery but if they ask you with foreach it would be
If it is direct from the php, Alvaro Vergara's answer is fine
You can use
json_decode
and loop through the array: