0

how can I select the number of "total_items" and the "average_price"?

JSON:

   {
  "status" : "success",
  "data" : {
    "items" : [
      {
        "market_hash_name" : "AK-47 | Redline (Field-Tested)",
        "total_items" : 698,
        "lowest_price" : "3.90",
        "highest_price" : "300.00",
        "cumulative_price" : "4669.62",
        "recent_sales_info" : {
          "hours" : "17.94",
          "average_price" : "4.23"
        }
      }
    ]
  }
}

Thats my PHP-Script:

$link = 'skin.json';
    $string = file_get_contents($link);
    $obj = json_decode($string, TRUE);
$name = $obj['items']['market_hash_name'];
$itmes = $name['total_items'];
$itmes = $name['average_price'];

How can I save the number of "total_items" and the "average_price" in variables? Thank You Regards. Enge

Enge
  • 113
  • 6
  • It seems that you'd access `$obj['data']['items'][0]['total_items']` and `$obj['data']['items'][0]['recent_sales_info']['average_price']`. – showdev May 17 '16 at 22:18

2 Answers2

1

Just like Andreas wrote, or :

// first, new variable (shorter lines/less depth afterwards)
$article = $obj['data']['items'][0];

// then 
$total_items = $article['total_items'];
$avg_price = $article['recent_sales_info']['average_price'];

Enge, note that "items": [ is an opening array within JSON object, that's the zero You were missing...

Spooky
  • 1,235
  • 15
  • 17
0

Try this:

$total_items = $obj['data']['items'][0]['total_items'];
$avg_price = $obj['data']['items'][0]['recent_sales_info']['average_price'];
  • A little bit off-topic, but that last name of yours, is it common? Had a lecturer with the same last name once. – Algernop K. May 17 '16 at 22:25
  • Is that right?: $link = 'skin.json'; $string = file_get_contents($link); $obj = json_decode($string, TRUE); $total_items = $obj['data']['items'][0]['total_items']; $avg_price = $obj['data']['items'][0]['recent_sales_info']['average_price']; echo $total_items; echo $avg_price; – Enge May 17 '16 at 22:30
  • @Enge Yes. You could echo it in an array instead, depending on the context – Algernop K. May 17 '16 at 22:31