How do I extract messages from this jsonobject with foreach or for? - PHP
$json = {"muestra":[{"mensaje1":"1-","mensaje2":"2-"},{"mensaje1":"3-","mensaje2":"4-"}]}
How do I extract messages from this jsonobject with foreach or for? - PHP
$json = {"muestra":[{"mensaje1":"1-","mensaje2":"2-"},{"mensaje1":"3-","mensaje2":"4-"}]}
First you need to create the string, in this case just surround the value of the json with the single quotes.
$json='{"muestra":[{"mensaje1":"1-","mensaje2":"2-"},{"mensaje1":"3-","mensaje2":"4-"}]}';
Then pass the string to the function json_decode()
which returns an object.
$jsonDecode=json_decode($json);
Finally, you pass the object to the% foreach
ck.
The first key ( $jsonDecode->muestra
) is the container of the array.
foreach($jsonDecode->muestra as $item) {
echo "Mensaje1 = {$item->mensaje1}<br>";
echo "Mensaje2 = {$item->mensaje2}<br>";
}
Here you can see it working (External link)