douyu7879 2013-11-04 23:21
浏览 124
已采纳

使用PHP解析JSON数据

I have parsed JSON data numerous times but for some reason cannot find the correct syntax to use when the data is nested. I am trying to parse the "assets" from this JSON but continue to get a invalid argument supplied foreach() regardless of what I try.

   "3435":{
      "name":"COLO-1014-SJ1",
      "nickname":"US-SJC-004",
      "type":"Colocated Server",
      "location":"San Jose:55 S Market",
      "assets":{
         "CPU":[
            {
               "model":"Intel E3 1270"
            }
         ],
         "Hard Drives":[
            {
               "model":"Western Digital 500GB RE4 ABYX SATA"
            },
            {
               "model":"Western Digital 500GB RE4 ABYX SATA"
            },
            {
               "model":"Kingston 240GB SSD"
            }
         ],
         "RAM":[
            {
               "model":"Super Talent 4GB DDR3 1333 ECC"
            },
            {
               "model":"Super Talent 4GB DDR3 1333 ECC"
            },
            {
               "model":"Super Talent 4GB DDR3 1333 ECC"
            },
            {
               "model":"Super Talent 4GB DDR3 1333 ECC"
            }
         ],

I would expect it to be something along the lines of...

$json = json_decode($jsondata, true);

foreach ($json as $item)
{
    foreach ($item['assets']->RAM as $asset)
    {
        echo $asset->model;
    }
  • 写回答

4条回答 默认 最新

  • donglijuan8227 2013-11-05 08:48
    关注

    From php official documentation: http://php.net/manual/fr/function.json-decode.php

    The 2nd func arg is for assoc array return. You can use it if you prefer to manipulate assoc array over object.

    But you actually mix array and object in your loop.

    If you keep the arg at TRUE, please use $item['assets']['RAM']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?