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.

0

2 Answers 2

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.