doumeng06063991 2014-08-06 11: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 11: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条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色