user1114748
user1114748

Reputation: 99

json values into php

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.

Upvotes: 0

Views: 54

Answers (3)

Capital C
Capital C

Reputation: 329

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.

Upvotes: 1

Tosho Trajanov
Tosho Trajanov

Reputation: 790

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'];
    }
}

Upvotes: 1

oshell
oshell

Reputation: 9103

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
    }
}

Upvotes: 1

Related Questions