当前位置:  开发笔记 > 编程语言 > 正文

解析具有未知字段名称的JSON数组?

如何解决《解析具有未知字段名称的JSON数组?》经验,为你挑选了1个好方法。

所以我有这个json:

{
  "success": true,
  "rgInventory": {
    "4580331488": {
      "id": "4580331488",
      "classid": "520025252",
      "instanceid": "0",
      "amount": "1",
      "pos": 1
    },
    "4566197481": {
      "id": "4566197481",
      "classid": "1439482117",
      "instanceid": "188530139",
      "amount": "1",
      "pos": 2
    },
    "4566196610": {
      "id": "4566196610",
      "classid": "1439484944",
      "instanceid": "188530139",
      "amount": "1",
      "pos": 3
    },
    "4566097797": {
      "id": "4566097797",
      "classid": "310776859",
      "instanceid": "302028390",
      "amount": "1",
      "    pos": 4
    },
    "4565915026": {
      "id": "4565915026",
      "classid": "310776840",
      "instanceid": "302028390",
      "amount": "1",
      "    pos": 5
    },
    "4565415060": {
      "id": "4565415060",
      "classid": "1439489161",
      "instanceid": "188530139",
      "amount": "1",
      "pos": 6
    },
    "4565413906": {
      "id": "4565413906",
      "classid": "1439484334",
      "instanceid": "188530139",
      "amount": "1",
      "pos": 7
    },
    "4559798755": {
      "id": "4559798755",
      "classid": "520025252",
      "instanceid": "0",
      "amount": "1",
      "pos": 8
    },
    "4553954652": {
      "id": "4553954652",
      "classid": "520025252",
      "instanceid": "0",
      "amount": "1",
      "pos": 9
    },
    "4553694029": {
      "id": "4553694029",
      "classid": "991959905",
      "instanceid": "0",
      "amount": "1",
      "pos": 10
    },
    "4553694015": {
      "id": "4553694015",
      "classid": "720289133",
      "instanceid": "188530170",
      "amount": "1",
      "    pos": 11
    },
    "4553694006": {
      "id": "4553694006",
      "classid": "1364486740",
      "instanceid": "188530139",
      "amount": "1",
      "pos": 12
    },
    "4553693992": {
      "id": "4553693992",
      "classid": "1309991239",
      "instanceid": "188530139",
      "amount": "1",
      "pos": 13
    },
    "4553693986": {
      "id": "4553693986",
      "classid": "310776711",
      "instanceid": "302028390",
      "amount": "1",
      "    pos": 14
    }
  }

我需要将它作为一个数组并解析它.问题是这个json来自我的库存,当我获取其他人的库存时,该字段将会改变,我无法弄清楚如何解析它.到目前为止我在这里:

$link='http://steamcommunity.com/profiles/'.$steamid.'/inventory/json/730/2';
$string = file_get_contents($link);
$obj = json_decode($string, true);
var_dump($obj['rgInventory']);

在这一点上我可以得到一个结果,但我不知道如何超越它,我的意思是,我需要返回每个记录的classid和实例id,但是这可以用JSON这样做吗?



1> 小智..:

你可以使用foreach循环

foreach ($obj['rgInventory'] as $key => $item) {
    echo $key; // echo the "unknown" field name
    echo $item['classid']; // echo any field value
}

推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有