HerrimanCoder
HerrimanCoder

Reputation: 7218

Access nested JSON value with PHP using object/arrow syntax

I have read a dozen stack posts on this topic and none of them work given my decoded JSON string. Here is my JSON:

{
   "id":"cus_EfVGU7XtvtKUx2",
   "account_balance":0,
   "cards":{
      "count":1,
      "data":[
         {
            "id":"card_1ECAFn2H1YALOWTjH0zGfOS7",
            "exp_month":11,
            "exp_year":2019,
            "last4":"1111",
            "metadata":[

            ],
            "name":"ned land",
            "type":"Visa"
         }
      ]
   },
   "invoice_prefix":"5F8A134",
   "has_more":false,
   "total_count":1,
   "url":"\/v1\/customers\/cus_EfVGU7XtvtKUx2\/sources"
}

Then I encode that string into an object:

$obj = json_decode($json, false);

I can easily get that top-most id value by doing this:

$obj->id

But when I try to get the exp_month value, I get back an empty string:

$expMonth = $obj->cards->data->exp_month;

Then alternatively I try array syntax:

$obj = json_decode($json, true);
$expMonth = $obj["cards"]["data"]["exp_month"];

And again $expMonth resolves to an empty string. What am I doing wrong?

Upvotes: 0

Views: 1207

Answers (2)

Sindhara
Sindhara

Reputation: 1473

data is an array of objects.

$obj->cards->data[0]->exp_month

should do the job

Upvotes: 1

ggorlen
ggorlen

Reputation: 56965

Use $expMonth = $obj->cards->data[0]->exp_month;. $data is an array.

Full example:

$obj = json_decode('{
   "id":"cus_EfVGU7XtvtKUx2",
   "account_balance":0,
   "cards":{
      "count":1,
      "data":[
         {
            "id":"card_1ECAFn2H1YALOWTjH0zGfOS7",
            "exp_month":11,
            "exp_year":2019,
            "last4":"1111",
            "metadata":[

            ],
            "name":"ned land",
            "type":"Visa"
         }
      ]
   },
   "invoice_prefix":"5F8A134",
   "has_more":false,
   "total_count":1,
   "url":"\/v1\/customers\/cus_EfVGU7XtvtKUx2\/sources"
}');

print_r($obj->cards->data[0]->exp_month);

Output is 11.

Upvotes: 2

Related Questions