在php中读取json层次结构

时间:2015-01-16 11:08:34

标签: php mysql json

我正在尝试使用以下json文件将json文件映射到mysql数据库:

configurationItems":[  
  {  
     "configurationItemVersion":"1.0",
     "configurationItemCaptureTime":"2014-12-05T10:22:51.751Z",
     "configurationStateId":1,
     "relatedEvents":[  ],
     "awsAccountId":"a value",
     "configurationItemStatus":"ResourceDiscovered",
     "resourceId":"some resource",
     "ARN":"blah blah",
     "awsRegion":"us-east-1",
     "availabilityZone":"us-east-1b",
     "configurationStateMd5Hash":"string",
     "resourceType":"AWS::EC2::Instance",
     "resourceCreationTime":"2014-01-06T10:37:37.000Z",
     "tags":{  },
     "relationships":[  ],
     "configuration":{  
        "instanceId":"",
        "imageId":"",
        "state":{  },
        "privateDnsName":"",
        "publicDnsName":"",
        "stateTransitionReason":"
        "keyName":"production-us",
        "amiLaunchIndex":0,
        "productCodes":[  ],
        "instanceType":"m2.xlarge",
        "launchTime":"ts",
        "placement":{  },
        "kernelId":"1",
        "monitoring":{  },
        "subnetId":"",
        "vpcId":"",
        "privateIpAddress":"",
        "stateReason":{  },
        "architecture":",
        "rootDeviceType":"",
        "rootDeviceName":"",
        "blockDeviceMappings":[  
           {  
              "deviceName":"namr",
              "ebs":{  
                 "volumeId":"vol-eb90e1a6",
                 "status":"attached",
                 "attachTime":"2014-01-06T10:37:40.000Z",
                 "deleteOnTermination":true
              }
           }
        ],
        "virtualization

我使用php访问的方式如下

$value_wanted=$parent["child1"]["child2"]["value"]; 

我在访问blockDeviceMappings设备名称时遇到问题,因为使用了我的理论,直到现在它才会出现

  $deviceName=$configurationItems["configuration"]["blockDeviceMappings"]    ["deviceName"];

我试过了

    $deviceName=$configurationItems["configuration"]["blockDeviceMappings"]   [""]["deviceName"];

但这不起作用,我认为它真的是空支架给我任何建议总是受到赞赏。

1 个答案:

答案 0 :(得分:1)

blockDeviceMappings是一个对象数组。如果它总是只有一个项目(如图所示):

$deviceName=$configurationItems["configuration"]["blockDeviceMappings"][0]["deviceName"];

否则你需要迭代数组:

foreach($configurationItems["configuration"]["blockDeviceMappings"] as $mapping)
    echo $mapping['deviceName'];

根据您的评论编辑,ebsdeviceName的兄弟姐妹而不是后代。

访问volumeId的正确方法是:

$deviceName=$configurationItems["configuration"]["blockDeviceMappings"][0]["ebs"]["volumeId"];