navigate through multidimensional PHP array by relative path

198 views Asked by At

I'm trying to use some JSON data in my website, but i got stuck while trying to read from.

Getting the data works well:

<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'));
?>

this is a little excerpt of the JSON data, but it lasts out to explain the problem

{
    "type": "champion",
    "format": "standAloneComplex",
    "version": "5.10.1",
    "data": {
        "Aatrox": {
            "version": "5.10.1",
            "id": "Aatrox",
            "key": "266",
            "name": "Aatrox",
            "title": "Die Klinge der Düsteren",
            "info": {
                "attack": 8,
                "defense": 4,
                "magic": 3,
                "difficulty": 4
            },
        },
        "Ahri": {
            "version": "5.10.1",
            "id": "Ahri",
            "key": "103",
            "name": "Ahri",
            "title": "Die neunschwänzige Füchsin",
            "info": {
                "attack": 3,
                "defense": 4,
                "magic": 8,
                "difficulty": 5
            },
        },
    }
}  

Question: How is it possible, to access the value of "key", without knowing the 'heading' (e.g. "Aatrox") ? I tried $data->{'data'}[0]->{'key'}, but that doesn't work.

Second Question: I also tried to search for the value of "key", but had no success in building the path with this method in PHP. A try with JavaScript worked well, but I would prefer to have a server-sided solution. Thanks for your help!

3

There are 3 answers

0
Duenna On

Personally I prefer to convert JSON object into the more PHP friendly Array.

If you use json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'))); You will be able to access the key value with something like this

$champions = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')));

foreach($champions['data'] as $key => $row){
    echo $row['key'];
}

This will echo your keys.

0
Johni On

Alternative very short way:

<?php
  $data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'), true);
  $first = current($data['data']);

More complete example:

<?php
  $data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'));
  $key = current($data->data)->key
0
amik On

If you want an element at particular 'offset', use

array_values($data->data)[0]->key;

otherwise, use foreach:

foreach ($data->data as $heading=>$data) {
    echo "The heading is $heading and key is {$data->key}";
}