Categories: php, json

PHP foreach loop with different offsets

2 answers

I want to extract certain parts from this api: Steamspy.com/api.php, However when I try to do a foreach loop I am getting a lot of errors.

Notice: Undefined offset: 0 in C:\Users\xx\Desktop\xx\Test\test.php on line 11 PHP Notice: Trying to access array offset on value of type null in C:\Users\xx\Desktop\xx\Test\test.php on line 11

I tried solving this by adding 1 after every loop but the all the games have different ID's in no particular order. How can I get my program to loop through all the arrays?

<?php $url = "https://steamspy.com/api.php?request=top100in2weeks"; $jsondata = file_get_contents("$url"); $json = json_decode($jsondata, true); $game = '0';  #$games = $json[220]['name']; #print_r($games);  foreach($json as $row) {     $json[$game]['name'];     $game += 1; } 

When I target a specific ID I am able to get the name of the game.

$games = $json[220]['name']; 

Please help me solve this, Thanks!

Received answers to this question:
The best answer according to the author of the question:
foreach ($json as $key => $row) {    var_dump($row); //[ 'appid':10, ... ]    var_dump($row['name']); //counter-strike, ...    var_dump($key); //10, 20, 30, ... } 

Try this

foreach ($json as $key => $value){     //$key = 220     //$value = the same as $json[$key]      $value['name'];     //THE SAME AS     $json[$key]['name']; }