从json解码数组中获取一个值

Ton*_*y33 1 php json

我有这个json编码的字符串

{"allresponses":"{\"id\":\"123456\",\"recipients\":1}"}
Run Code Online (Sandbox Code Playgroud)

我只需要获取id并将其传递给php变量.

这就是我正在尝试的:假设我在变量返回中有该字符串,所以:

$return = '{"allresponses":"{\"id\":\"123456\",\"recipients\":1}"}';
$getid = json_decode($return,true);
echo $getid[0]['id'];
Run Code Online (Sandbox Code Playgroud)

这不起作用; 我得到了致命的错误.你能告诉我为什么吗?怎么了?

Mar*_*c B 5

你有json-in-json,这意味着它的值allresponses本身就是一个json字符串,必须单独解码:

$return = '{"allresponses":"{\"id\":\"123456\",\"recipients\":1}"}';
$temp = json_decode($return);

$allresp = $temp['allresponses'];
$temp2 = json_decode($allresp);

echo $temp2['id']; // 123456
Run Code Online (Sandbox Code Playgroud)

请注意,您$getid[0]的错误.你没有阵列.json纯粹是object({...}),因此没有[0]索引可以访问.甚至一些基本的调试var_dump($getid)就会向你展示这一点.