0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

data is an array of objects.

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

should do the job

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.