PHP Undefined Index When Decoding From Json PHP Undefined Index When Decoding From Json json json

PHP Undefined Index When Decoding From Json


Access your code like this

$games = $data[0]['totalGamesPlayed'];

Code for getting other info

<?php$json = 'PUT YOUR EXAMPLE JSON HERE';$data = json_decode($json,true); $seasonWon = 0;$seasonPlayed = 0;foreach($data as $stats) {    if($stats['championId'] != 0) {        echo '<br><br>Total Games Played:'. $stats['totalGamesPlayed'];            echo '<br>champion Ids :'.$stats['championId'];        foreach($stats['stats'] as $stat) {            if($stat['statType'] == 'TOTAL_SESSIONS_WON') {                $seasonWon = $stat['value'];                echo '<br>TOTAL_SESSIONS_WON :'.$seasonWon;            }            if($stat['statType'] == 'TOTAL_SESSIONS_LOST')            echo '<br>TOTAL_SESSIONS_LOST :'.$stat['value'];            if($stat['statType'] == 'TOTAL_SESSIONS_PLAYED') {                                $seasonPlayed = $stat['value'];                echo '<br>TOTAL_SESSIONS_PLAYED :'.$seasonPlayed;                            }        }        echo '<br>Games Ratio(TOTAL_SESSIONS_WON / TOTAL_SESSIONS_PLAYED): ('. $seasonWon.'/'.$seasonPlayed.'):'. ($seasonWon/$seasonPlayed);    }}


In case of problems like yours, it's handy to peek what your decode data really looks like. So instead of blindly reading, use print_r() or var_dump() to look. print_r($data); would output:

Array(    [0] => Array        (            [totalGamesPlayed] => 25            [championId] => 0        ))

therefore the correct "path" is:

$games = $data[0]['totalGamesPlayed'];

This is so, because your JSON object is array (first and last character of JSON is [ and ]) with object as array node ({/}) and your real values are members of that object. You can fix that by checking why you construct JSON that way in the first place (maybe code allows more elements of array), or "extract" object to get rid of being forced to use [0] in references:

$data = $data[0];$games = $data['totalGamesPlayed'];

and print_r($data) would give:

Array(    [totalGamesPlayed] => 25    [championId] => 0)

and your former code will start to work:

$games = $data['totalGamesPlayed'];echo $games;

gives

25


Have you try this:

$games = $data[0]['totalGamesPlayed'];

The problem is your json is an array with it first element is an object