Connor Connor - 1 year ago 64
JSON Question

Parsing JSON in for each with increment PHP

I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?

Here is the json file tidied up so you can see what I mean -

I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]

// get ergast json feed for next race
$url = "";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);

$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];

Answer Source

While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.

$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;

foreach($nextRaceDate as $race){
    echo 'Race number : ' . $race->number . '<br>';
    echo 'Race Points : ' . $race->number . '<br>';
    echo '===================='  . '<br>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download