简体   繁体   中英

How can I access .json data in PHP?

I have a .json file. I want to access this data in my .php file. I have a variable $spellId, for example: $spellId="SummonerBarrier";

I want to get "name" from the .json file just by having $spellId. Any idea how I can do this?

I know there are a lot of questions like this here, but i do not how to make the solutions with my code.

{
    "type": "summoner",
    "version": "6.3.1",
    "data": {
        "SummonerBarrier": {
            "id": "SummonerBarrier",
            "name": "Barrier",
            "description": "Shields your champion for 115-455 (depending on champion level) for 2 seconds.",
            "tooltip": "Temporarily shields {{ f1 }} damage from your champion for 2 seconds.",
            "maxrank": 1,
            "cooldown": [
                210
            ]
        },
        "SummonerBoost": {
            "id": "SummonerBoost",
            "name": "Cleanse",
            "description": "Remove..."
        }
    }
}

Try this:

$data = '{
    "type": "summoner",
    "version": "6.3.1",
    "data": {
        "SummonerBarrier": {
            "id": "SummonerBarrier",
            "name": "Barrier",
            "description": "Shields your champion for 115-455 (depending on champion level) for 2 seconds.",
            "tooltip": "Temporarily shields {{ f1 }} damage from your champion for 2 seconds.",
            "maxrank": 1,
            "cooldown": [
                210
            ]
        },
        "SummonerBoost": {
            "id": "SummonerBoost",
            "name": "Cleanse",
            "description": "Remove..."
        }
    }
}';

$decoded = json_decode($data);
var_dump($decoded->data->SummonerBarrier->name);
$array = json_decode($json, true);

foreach ($array['data'] as $key => $value) {
    echo "$key:$value[name]<br />";
}
$decodeData = json_decode($data);
$spellId="SummonerBarrier";
$nameToFetch=$decodeData->data->$spellId->name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM