我有以下代码,我想要做的是从" total_reviews"获取json值。进入一个php变量,我们可以调用$ total_reviews。
然而,正在发生的事情是我收到的错误是Notice: Undefined property: stdClass::$total_reviews
这是我的代码
//URL of targeted site
$url = "https://api.yotpo.com/products/$appkey/467/bottomline";
// Initiate curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
$data = json_decode($result);
echo "e<br />";
echo $data->total_reviews;
// close curl resource, and free up system resources
curl_close($ch);
?>
如果我print_r结果我打印出来
{"status":{"code":200,"message":"OK"},"response":{"bottomline":{"average_score":4.2,"total_reviews":73}}}
答案 0 :(得分:3)
如果您希望将JSON数据作为数组,请使用json_decode()
上的第二个参数将数据转换为数组。
$data = json_decode($result, true);
如果你想要传递给你的JSON数据,我认为它是一个对象然后使用
$data = json_decode($result);
echo "<br />";
echo $data->total_reviews;
但无论如何,如果这是你的JSON字符串,
{"status":
{
"code":200,
"message":"OK"
},
"response":
{
"bottomline":
{
"average_score":4.2,
"total_reviews":73
}
}
}
然后total_reviews
值为
echo $data->response->bottomline->total_reviews;
或者如果您使用参数2将完美的对象转换为数组
echo $data['response']['bottomline']['total_reviews'];
答案 1 :(得分:1)
json_decode()
默认提取到stdClass对象。如果你想要一个数组,传递一个truthy值作为第二个参数:
$data = json_decode($result, true);