doumeng06063991 2014-08-06 11:15
浏览 1061
已采纳

使用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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题