【问题标题】:Json api decodingJson api解码
【发布时间】:2016-05-22 00:10:05
【问题描述】:

这是我的 json

{
  "rgInventory": {
           "5455029633": {
                           "id":"5455029633",
                           "classid":"310776543",
                           "instanceid":"302028390",
                           "amount":"1"
            }
  }
}

这是我在php中解析json的方式

$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content);
foreach($decode->rgInventory->5455029633  as $appid){
    echo $appid->id;
}

我需要得到那个 5455029633,但它在 foreach 中不起作用。
我也想将它存储在变量中。

【问题讨论】:

    标签: php html json decode


    【解决方案1】:

    您提供的 JSON 无效。从"amount":"1", 中删除最后一个逗号,并且您缺少右花括号。然后您应该能够以$decode->rgInventory->{"5455029633"} 访问所需的值。

    或者让你的生活更简单;)然后选择 assoc 数组 $decode = json_decode($content, true);

    【讨论】:

    • 如果我有数百个完全不同的“5455029633”,我需要全部回显或将其放入变量中怎么办?
    • 正如我所写,您可以使用 assoc 数组而不是对象,然后一切都变得微不足道。或者您可以使用 stdclass 并迭代其属性,如下所示:php.net/manual/en/language.oop5.iterations.php - 标准循环运行良好:php > foreach ($decode->rgInventory as $key => $v) {var_dump($key);} string(10) "5455029633"
    【解决方案2】:

    您需要将 true 作为第二个参数传递给函数 json_decode 以获取数组而不是对象:

    PHP

    <?php
      $content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
      $decode = json_decode($content, true);
      echo $decode['rgInventory']['6255037137']['id']; // will output the property 'id' of the inventory 6255037137
      $invetory = $decode['rgInventory']['6255037137'] // will store the inventory 6255037137 in the variable $inventory
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-27
      • 2013-05-01
      • 2012-03-22
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多