Francisco Panis Kaseker Francisco Panis Kaseker -4 years ago 138
JSON Question

How to access array inside document using PHP

I want print specific vars from array inside a document.

JSON structure:

{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}


I am trying to do this in PHP (and already decoded that json). How can I access and print all ids using foreach or for?

I can not understand how I can manage "return" scope.

Answer Source

Json decode to array:

$json = json_decode($strjson, true); // decode the JSON into an associative array

and

echo "<pre>"; 
print_r($json);

And foreach:

foreach ($json as $key => $value) {
    echo $key . " ". $value. "<br>";
}

Working example:

$json = '{ 
 "return": {
    "string": "2222",
    "contacts": [
        {
            "contact": {
              "id": "09890423890"
               }
        },
        {
            "contact": {
              "id": "2423444"
               }
        },
        {
            "contact": {
              "id": "24242423"
               }
        }        
      ]
   }
}';
$json = json_decode($json, true);
print_r($json);
foreach ($json['return']['contacts'] as $val) {
    echo $val['contact']['id']."<br>";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download