Reputation: 147
I have this json encoded string
{"allresponses":"{\"id\":\"123456\",\"recipients\":1}"}
and I have to get the id only and pass it to a php variable.
This is what I'm trying: suppose I have that string in variable return, so:
$return = '{"allresponses":"{\"id\":\"123456\",\"recipients\":1}"}';
$getid = json_decode($return,true);
echo $getid[0]['id'];
This is not working; I get fatal error. Can you tell me why? What's wrong?
Upvotes: 1
Views: 636
Reputation: 360662
You've got json-in-json, which means that the value for allresponses
is itself a json string, and has to be decoded separately:
$return = '{"allresponses":"{\"id\":\"123456\",\"recipients\":1}"}';
$temp = json_decode($return);
$allresp = $temp['allresponses'];
$temp2 = json_decode($allresp);
echo $temp2['id']; // 123456
Note that your $getid[0]
is WRONG. You don't have an array. The json is purely objects ({...}
), therefore there's no [0]
index to access. Even some basic debugging like var_dump($getid)
would have shown you this.
Upvotes: 5