简体   繁体   English

使用PHP解析多维嵌套JSON

[英]Parsing Multidimensional Nested JSON with PHP

I feel like i am slightly insane, and I have certainly read the docs on this. 我觉得我有点发疯,并且我当然已经阅读了有关此文档。 I am completely unable to echo out various objects in a JSON array in PHP. 我完全无法在PHP中回显JSON数组中的各种对象。 I am not sure what I'm doing wrong, but I'm ripping my hair out... 我不确定自己做错了什么,但是我正在扯头发...

Here is my JSON array: 这是我的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"
}

I know this is simple, but I can't get it right. 我知道这很简单,但我做对了。 I would like to echo out four different values. 我想表达四个不同的价值观。

This is what I have been trying: 这就是我一直在尝试的:

$photoId = $jsonDecoded['photos']['photo'][0]['id'];
$photoSecret = $jsonDecoded['photos']['photo'][0]['secret'];
$photoServer = $jsonDecoded['photos']['photo'][0]['server'];
$photoFarm = $jsonDecoded['photos']['photo'][0]['farm'];

I know this seems newbie. 我知道这似乎是新手。 Please help... 请帮忙...

Best, 最好,

if there are multiple photo sub arrays then you can do like this. 如果有多个照片子阵列,则可以这样做。

//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'];

}

The problem is that you have both objects and arrays in your json, but are using array syntax in your php. 问题是您在json中同时拥有对象和数组,但是在php中使用了数组语法。

There are two ways to fix this, 1st simply set the second parameter of json_decode to true: 有两种方法可以解决此问题,第一种方法只是将json_decode的第二个参数设置为true:

json_decode($json, true);

This will create a multidimentional array you can access as suggested in your question, eg: 这将创建一个多维数组,您可以根据问题中的建议进行访问,例如:

$photoId = $jsonDecoded['photos']['photo'][0]['id'];

Alertinitivly you can use object property syntax on your existing $jsonDecoded: Alertinitivly可以在现有$ jsonDecoded上使用对象属性语法:

$photoId = $jsonDecoded->photos->photo[0]->id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM