Tony33 Tony33 - 3 years ago 148
JSON Question

get a value from json decoded array

I have this json encoded string


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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download