0

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.

3 Answers3

3

You can decode the json contents and use it like an array. This should work:

$json = json_decode($string, true);
$contacts = $json['return']['contacts'];

foreach($contacts as $contact){
  echo $contact['contact']['id'];
}
2

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>";
}
1

Try this code:

$json ='
{ 
 "return": {
    "string": "2222",
    "contacts": [
        {
            "contact": {
              "id": "09890423890"
               }
        },
        {
            "contact": {
              "id": "2423444"
               }
        },
        {
            "contact": {
              "id": "24242423"
               }
        },
        etc
      ]
   }
}
';
   $array = json_decode($json,TRUE);
foreach($array['return']['contacts'] as $value ){
echo $value['id'];
}

Use file_get_contents function if you want to pull data from file.

TML
  • 11
  • 2