How to extract an array from a JsonObject in php

2

How do I extract messages from this jsonobject with foreach or for? - PHP

$json = {"muestra":[{"mensaje1":"1-","mensaje2":"2-"},{"mensaje1":"3-","mensaje2":"4-"}]}
    
asked by JoelRomero 04.08.2018 в 17:03
source

1 answer

2

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)

    
answered by 04.08.2018 / 17:45
source