A
A
Anton Neverov2016-07-19 07:16:27
PHP
Anton Neverov, 2016-07-19 07:16:27

How to display the desired value from a specific JSON array using PHP?

Hello!
There is a JSON array that is loaded from a third-party resource:

{
  "playerstats": {
    "steamID": "76561197972495328",
    "gameName": "ValveTestApp260",
    "stats": [
      {
        "name": "total_kills",
        "value": 2199
      },
      {
        "name": "total_deaths",
        "value": 1501
      },
      {
        "name": "total_time_played",
        "value": 115235
      }
    ]
  }
}

I get the value from it like this:
$json_csgo_user_info = file_get_contents('http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key='.$steam_api_key.'&steamid='.$user_steam_id); //Получение JSON
$json_csgo_user_info = json_decode($json_csgo_user_info)->playerstats->stats;
echo $json_csgo_user_info[1]->value; //Вывод

But it seems to me that this is wrong. Suddenly, the sequence of parameters will change. Is it possible to make the output of the value "value" not depending on the sequence, but depending on the "name" parameter?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2016-07-19
@TTATPuOT

Вы правы, так действительно лучше не делать.
Но удобного способа сделать это на php нет.
Вы можете:

  • Подключить библиотеку для работы с коллекциями (например пакет Collection из Laravel). На средних и крупных проектах я предпочитаю именно такой путь, чтобы не изобретать велосипед.
  • Использовать array_filter в комбинации с reset.
  • Обходить элементы массива циклом и прерывать его, когда найден нужный элемент.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question