Vibbo Vibbo - 4 days ago 5
JSON Question

Get specific data in variable array JSON with jQuery PHP

I'm trying to get specific data from a JSON file (url) and save that data in a PHP variable.

The JSON comes from an url. For example:
https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Viducius?api_key=secret

The JSON file:

{
"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}


So my question is how can I get the data from
id
, in this case
26541044
, and put that into a PHP variable?

Also to get the data from the JSON file, I have to search for the
id
while the array name 'viducius' came from a PHP variable.

TLDR:
The array $arrayName contains an id '26541044' that has to be saved into variable $id

Is there someone who can help me with this? I was thinking on doing this in jQuery but if it's easier with PHP only thats fine too.

Answer

That is a JSON String, therefore you need to convert it into a PHP data structure. PHP Provides json_decode() to do that.

$json_string = '{"viducius": {
                       "id": 26541044,
                       "name": "Viducius",
                       "profileIconId": 591,
                       "revisionDate": 1480517139000,
                       "summonerLevel": 30
                    }
                }';

$obj = json_decode($json_string);
$id = $obj->viducius->id;

echo 'id = ' . $id;
Comments