我觉得我有点疯了,我当然看过关于这方面的文档。我完全无法在PHP中回显JSON数组中的各种对象。我不知道我做错了什么,但是我把头发都扯掉了。
这是我的JSON数组:
{
"photos": {
"page": 1,
"pages": 1569045,
"perpage": 1,
"total": "1569045",
"photo": [
{
"id": "14842817422",
"owner": "23432140@N06",
"secret": "c37cfa1914",
"server": "3864",
"farm": 4,
"title": "pizza",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
},
"stat": "ok"
}
我知道这很简单,但是我做不对。我想回显四个不同的值。
这就是我一直在尝试的:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
$photoSecret = $jsonDecoded['photos']['photo'][0]['secret'];
$photoServer = $jsonDecoded['photos']['photo'][0]['server'];
$photoFarm = $jsonDecoded['photos']['photo'][0]['farm'];
我知道这看起来很新手。请帮助…
,
问题是你在json中有对象和数组,但在php中使用数组语法。
有两种方法可以解决这个问题,第一种方法是将json_decode的第二个参数设置为true:json_decode($json, true);
这将创建一个多维数组,您可以按照问题中的建议访问,例如:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
首先,您可以在现有的$jsonDecoded:
上使用对象属性语法。$photoId = $jsonDecoded->photos->photo[0]->id;
如果有多个photo子数组,那么您可以这样做。
//this will create array instead of object
$jsonDecoded = json_decode($your_feed_data,true);
foreach($jsonDecoded['photos']['photo'] as $sub_array){
$photoId = $sub_array['id'];
$photoSecret = $sub_array['secret'];
$photoServer = $sub_array['server'];
$photoFarm = $sub_array['farm'];
}