1

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?

1 Answer 1

5

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.

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

5 Comments

Obviously, this madness should be fixed at the source, not by double decoding…
the problem is i use an API that gives me that source, so i can't fix it, lol. About $getid[0] , i used "true" in json_encode statement to make it as associated array, shouldn't it be converted form obj to array then? Ayway, i'm getting Fatal error: Cannot use object of type stdClass as array
it'll be a php array, but that still doesn't create a [0] index.
Fatal error: Cannot use object of type stdClass as array. adding ",true" at every json_decode , fixes the problem. :)
ah yeah. you have to DECODE to an assoc array: json_decode(...,true) as well. JS doesn't have associated arrays. it has objects. arrays are ALWAYS numerical-keyed, sequentially. if you have an array missing indexes, then it HAS to be encoded as an object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.