doumeng06063991 2014-08-06 03:15
浏览 1063
已采纳

使用PHP解析多维嵌套JSON

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. I am not sure what I'm doing wrong, but I'm ripping my hair out...

Here is my JSON array:

{
    "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,

展开全部

  • 写回答

2条回答 默认 最新

  • dsrbb20862 2014-08-06 03:27
    关注

    The problem is that you have both objects and arrays in your json, but are using array syntax in your php.

    There are two ways to fix this, 1st simply set the second parameter of json_decode to 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:

    $photoId = $jsonDecoded->photos->photo[0]->id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部