0

here is my json

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

Here is my way to parse json in php

$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;
}

I need to get that 5455029633 but it dont work in foreach.
And I want to store it in the variable too.

2 Answers 2

2

Json, which you've provided is invalid. Remove last comma from "amount":"1", and you are missing closing curly bracket. Then you should be able to access desired value as $decode->rgInventory->{"5455029633"}.

Or make your life simpler ;) and just go for assoc array $decode = json_decode($content, true);

Sign up to request clarification or add additional context in comments.

2 Comments

What if I have hundreds of "5455029633" that are all different and i need to echo all or get it into variable?
As I wrote, you can go for assoc array instead of object, and then everything is trivial. Or you can stay with stdclass and iterate through its properties as shown here: php.net/manual/en/language.oop5.iterations.php - standard loop works well: php > foreach ($decode->rgInventory as $key => $v) {var_dump($key);} string(10) "5455029633"
0

You will need to pass true as second argument to the function json_decode to get an array instead of an object :

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

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.