【问题标题】:Foreach item JSON decode in PHP?PHP中的Foreach项目JSON解码?
【发布时间】:2015-03-14 12:32:35
【问题描述】:

我正在尝试做一些 CS: Global Offensive 清单以供个人体验。现在我不知道应该如何显示库存中的所有物品。

库存 JSON

{
    "success":true,
    "rgInventory":{
            "1847345369":{
                    "id":"1847345369",
                    "classid":"638241994",
                    "instanceid":"188530139",
                    "amount":"1","pos":1
                    },
            "1844330224":{
                    "id":"1844330224",
                    "classid":"469444104",
                    "instanceid":"0",
                    "amount":"1","pos":2
                    }
    }
}

所以当我想要第一个项目的 id 时,我必须使用它

$item = $parsed_json->{'rgInventory'}->{'1847345369'}->id;

但是在 json 解析中使用 itemid 是愚蠢的。我怎样才能让它列出所有项目的 ID?

【问题讨论】:

    标签: php json steam steam-web-api


    【解决方案1】:

    使用foreach() 循环。

    <?php
    
    $items = array();
    
    foreach($parsed_json->{'rgInventory'} as $key => $obj) {
        // $key now holds '1844330224' etc
        $items[] = $obj->id; // or re-use $key here ;-)
    }
    
    ?>
    

    【讨论】:

      【解决方案2】:

      使用数组代替对象。

      "rgInventory":[
          { "id":"1847345369", ...}, 
          { "id":"1844330224", ...}
      ]
      

      然后使用索引获取([0]等)

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2018-05-14
      • 2016-08-03
      • 2014-08-01
      • 1970-01-01
      • 2020-07-12
      相关资源
      最近更新 更多