嵌套的JSON PHP解码

时间:2015-09-08 08:40:15

标签: php json

我有以下Json文件

{
    "username”: “userabc”,
    “locations”: [
        {
            “locationId": "2123",
            “locationName": "Test Site",
            “setupDate”: "0000-00-00",
            “dataType”: {
                “book”: [
                    {
                        “bookId": “1257245",
                        “information”: “Infotag 181”,
                        “addedDate": "0000-00-00 00:00:00"
                    },
                    {
                        “bookId": “4257245",
                        “information”: “Infotag 11”,
                        “addedDate": "0000-00-00 00:00:00"
                    },
                    {
                        “bookId": “2227242”,
                        “information”: “Infotag 181”,
                        “addedDate": "0000-00-00 00:00:00"
                    }
                ],
                “tape”: [
                    {
                        “tapeId": “1220”,
                        “information”: “Infotag 181”,
                        “addedDate": "0000-00-00 00:00:00"
                    },
                    {
                        “tapeId": “1320”,
                        “information”: “Infotag 181”,
                        “addedDate": "0000-00-00 00:00:00"
                    }
                ],
                “record”: [
                    {
                        “recordId": “a21322”,
                        “information”: “Infotag 181”,
                        “addedDate": "0000-00-00 00:00:00"
                    },
                    {
                        “recordId": “b213222”,
                        “information”: “Infotag 181”,
                        “addedDate": "0000-00-00 00:00:00"
                    }
                ],
                "virtual": [
                    {
                        “virtId": "2123",
                        “information”: "57235",
                        “addedDate”: "0000-00-00 00:00:00",

                    }
                ]
            }
        }
    ]
}

我目前正在尝试访问嵌套部分(计算bookID的数量)。我已经完成了以下操作,可以打印locationName,但我无法打印bookId,我不知道我哪里出错了。

$obj = json_decode($json,true);

foreach($obj['locations'] as $chunk) {
  $locName = $chunk['locationName'];
  echo $locName;
}

这是我遇到问题的部分,我无法看到任何结果?

foreach($obj['locations']['book'] as $chunk) {
  $bkId = $chunk['bookId'];
  echo $bkId;
}

1 个答案:

答案 0 :(得分:1)

$obj['locations']是一个集合。您希望使用foreach对其进行迭代,或者只使用$obj['locations'][0]访问第一个元素。即您访问$obj['locations'][0]['books']

如果您使用error_reporting(0);ini_set('display_errors', true);运行代码,当您访问阵列中不存在的密钥时会收到警告,因此您会被告知这里有什么问题