所以我要从如下所示的JSON格式的URL中获取数据。
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
// And So on upto 10 id places.
现在,我要使用cURL php在我的网站中获取数据。
我的php代码如下:
$url = "https://jsonplaceholder.typicode.com/users" ;
$ch = curl_init() ;
curl_setopt($ch, CURLOPT_URL, $url) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch) ;
$id = 1;
$data = json_decode($result) ;
foreach ($data as $mydata) {
if ($mydata["id"] == $id) {
echo $mydata["address"]["street3"] ;
break ;
}
}
但是我得到的是一个错误:
不能将stdClass类型的对象用作数组
答案 0 :(得分:0)
second param为TRUE时,返回的对象将转换为关联数组。
$data = json_decode($result,true) ;
foreach ($data as $mydata) {
if ($mydata["id"] == $id) {
echo $mydata["address"]["street"] ;//changes `street3` is not there
break ;
}
}
默认情况下,json_decode将返回您的对象,如果您想使用
[]
语法,则需要关联数组,并且仅为此需要传递第二个参数true
,请参阅此 json_decode用于进一步查询