Error catching field of a JSON?

3

I'm having an error when I try to retrieve a field from a array .

Follow json :

{
      "data": {
        "messages": [
          {
            "id": 1,
            "sender": "[email protected]",
            "recipient": "[email protected]",
            "sent_at": "2015-01-22T18:17:53.586-02:00",
            "status": "delivered",
            "bounce_code": null,
            "subject": "teste"
          },
          {
            "id": 2,
            "sender": "[email protected]",
            "recipient": "[email protected]",
            "sent_at": "2015-01-22T18:17:53.686-02:00",
            "status": "bounced",
            "bounce_code": "5.1.1",
            "subject": "test2"
          }
        ]
      },
      "links": {
        "self": "http://api.smtplw.locaweb.com.br/v1/message_reports?end_date=2015-04-10&page=2&per=2&start_date=2015-01-01&status=all",
        "next": "http://api.smtplw.locaweb.com.br/v1/message_reports?end_date=2015-04-10&page=3&per=2&start_date=2015-01-01&status=all",
        "prev": null,
        "first": "http://api.smtplw.locaweb.com.br/v1/message_reports?end_date=2015-04-10&page=1&per=2&start_date=2015-01-01&status=all",
        "last": "http://api.smtplw.locaweb.com.br/v1/message_reports?end_date=2015-04-10&page=5&per=2&start_date=2015-01-01\u0026status=all"
      }
    }

My PHP looks like this:

$jsonObj = json_decode($VARIAVEL_COM_O_JSON);
$resposta = $jsonObj->data;

foreach ($resposta as $c) {
    echo "$c->recipient<br>"; 
}

The error that occurs:

  

Notice: Trying to get property of non-object in /Library/WebServer/Documents/teste.php on line 24

Error line:

echo "$c->recipient<br>"; 

I need to write all fields recipient of array ?

    
asked by anonymous 27.10.2016 / 15:13

2 answers

5

In your foreach it looks like this:

foreach ($resposta->messages as $c) {
    echo "$c->recipient<br>"; 
}

What was happening was that your foreach was only passing the index date, so the first loop always returned the array that was assigned to the messages index, so it will loop with that array.

    
27.10.2016 / 15:16
3

Your Json has several levels here you only enter level 1

$resposta = $jsonObj->data; 

Inside it has messages and links

You need to tell the next level to iterate

foreach ($resposta->messages as $c) {
    echo "$c->recipient<br>"; 
}
    
27.10.2016 / 15:46