0

I'm trying to use the RIOT API but I'm kinda stuck. So here's the output of the page :

{
"36694730": [{
    "name": "Twitch's Marksmen",
    "tier": "GOLD",
    "queue": "RANKED_SOLO_5x5",
    "entries": [{
        "playerOrTeamId": "36694730",
        "playerOrTeamName": "OU2S",
        "division": "V",
        "leaguePoints": 0,
        "wins": 207,
        "losses": 201,
        "isHotStreak": false,
        "isVeteran": false,
        "isFreshBlood": true,
        "isInactive": false
    }]
}]}

What I've actually tried to do is :

<?php
$link = "https://euw.api.pvp.net/api/lol/euw/v2.5/league/by-summoner/36694730/entry?api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$json = file_get_contents($link);

$get = json_decode($json, true);
// echo $get['name'];
echo $get->name;

?>

Both didn't work for me, thanks for taking the time to read this.

  • 1
    done any basic debugging, like `var_dump($json, $get)` to see what you actually received? You're just assuming nothing could ever go wrong with this code, which is exactly the WRONG attitude to have. Never EVER assume success when dealing with external resources. Always assume failure, check for failure, and treat success as a pleasant surprise. Even if your PHP is 100% syntactically correct, what if that's the wrong url? What if that site is down, or there's a network glitch between your machine and that site? – Marc B Aug 22 '16 at 14:25
  • I'd use CURL to do that call... – Eric Aug 22 '16 at 14:26

3 Answers3

1

You cannot access the property directly. You have to go into the array after decoding.

foreach ($get as $response) {
    foreach ($response as $element) {
        echo $element['name']; //Twitch's Marksmen
    }
}
oshell
  • 8,923
  • 1
  • 29
  • 47
1

There is a multi-dimensional array as a response from json_decode. You should go this way -

$get = json_decode($json, true);
foreach ($get as $firstElement) {
    foreach ($firstElement as $secondElement) {
        echo $secondElement['name'];
    }
}
Tosho Trajanov
  • 790
  • 8
  • 19
1

Since your are decoding the data to an array (2nd parameter of json_decode set to true). Your decoded array should be like this,

Array
(
    [36694730] => Array
    (
        [0] => Array
        (
            [name] => Twitch's Marksmen
            [tier] => GOLD
            [queue] => RANKED_SOLO_5x5
            [entries] => Array
            (
                [0] => Array
                (
                    [playerOrTeamId] => 36694730
                    [playerOrTeamName] => OU2S
                    [division] => V
                    [leaguePoints] => 0
                    [wins] => 207
                    [losses] => 201
                    [isHotStreak] => 
                    [isVeteran] => 
                    [isFreshBlood] => 1
                    [isInactive] => 
                )
            )
        )
    )
)

Your code should be:-

echo $get['36694730']['0']['name'];

Hope this helps.

Capital C
  • 319
  • 3
  • 13