将json字符串转换为php变量

问题描述 投票:0回答:2

我有下面的代码,我想要做的是从“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}}}
php json
2个回答
3
投票

如果您希望将JSON数据作为数组,则使用json_decode()上的第二个参数使其将数据转换为数组。

$data = json_decode($result, true);

如果你想要传递给你的JSON数据,我认为它是一个Object然后使用

$data = json_decode($result);

echo "<br />";
echo $data->total_reviews; 

json_decode() manual page

但不管怎样,如果这是你的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
投票

json_decode()默认提取到stdClass对象。如果你想要一个数组,传递一个truthy值作为第二个参数:

$data = json_decode($result, true);
© www.soinside.com 2019 - 2024. All rights reserved.