Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Undefined Index When Decoding From Json

I am trying to Json decode something and get the value I want. But I get PHP undefined index error. This is my code.

<?php
$json = '[{"totalGamesPlayed":25,"championId":0}]';
$data = json_decode($json,true); 

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

The problem is the "[" "]" are messing with my code... I am using an API to get some values. What I get is this : http://pastebin.com/XrqkAbJf I need the totalGamesPlayed,the champion ID's except zero (82,106 and 24) and the TOTAL_SESSIONS_WON and TOTAL_SESSIONS_LOST for these ID's... For a start, let's find out how can I bypass the "[" and "]" symbols,and then things may be easier.. Thank you in advance!

like image 853
Xazo Skoulhki Avatar asked Dec 02 '12 06:12

Xazo Skoulhki


People also ask

How to display JSON decode data in PHP?

Decoding JSON data in PHP: It is very easy to decode JSON data in PHP. You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value.

How to parse JSON to array in PHP?

The json_decode() is an inbuilt function in php which is used to convert JSON encoded string to appropriate variable in php. Generally, json_decode is used to convert json to array in PHP but it has other usecases as well. Parameters: json: The JSON string passed to be decoded to php variable.

What does JSON_ decode return?

The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.

What is JSON_ encode in PHP?

json_encode(mixed $value , int $flags = 0, int $depth = 512): string|false. Returns a string containing the JSON representation of the supplied value . If the parameter is an array or object, it will be serialized recursively.


3 Answers

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);
    }
}
like image 69
Pankaj Khairnar Avatar answered Oct 22 '22 11:10

Pankaj Khairnar


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
like image 36
Marcin Orlowski Avatar answered Oct 22 '22 12:10

Marcin Orlowski


Have you try this:

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

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

like image 25
goFrendiAsgard Avatar answered Oct 22 '22 13:10

goFrendiAsgard