user7137459
user7137459

Reputation:

PHP access array value with name

I'm trying to make a PHP website that gets information out of (a large) array.

The array looks like this:

"playerstats": {
        "steamID": "MyID",
        "gameName": "ValveTestApp260",
        "stats": [
            {
                "name": "total_kills",
                "value": 35342
            },
            {
                "name": "total_deaths",
                "value": 30465
            },
            {
                "name": "total_time_played",
                "value": 1952281
            so on and so on...

The way I'm accessing it right now is by using:

$kills = $jsonforgame['playerstats']['stats'][0]['value'];
$deaths = $jsonforgame['playerstats']['stats'][1]['value'];

the problem is that I have hundreds of 'stats' in the array, is there a way to access all the value's with the name (like total_kills & total_deaths) instead of having to count all the arrays?

Thanks for reading :)

Upvotes: 0

Views: 98

Answers (3)

tjfo
tjfo

Reputation: 1189

You could change the structure of your stats array to use the stat name as the array key like so:

"playerstats": {
    "steamID": "MyID",
    "gameName": "ValveTestApp260",
    "stats": {
        "total_kills": 35342,
        "total_deaths": 30465,
        "total_time_played": 1952281
    }
}

Then you can access with

$kills = $jsonforgame['playerstats']['stats']['total_kills'];

Upvotes: 0

Rafael Araújo
Rafael Araújo

Reputation: 201

Use array_search:

$stats_array = $jsonforgame['playerstats']['stats'];
$key = array_search('total_deaths', array_column($stats_array, 'name'));
$deaths = $stats_array[$key]['value'];

echo var_dump($key).PHP_EOL;
echo var_dump($stats_array[$key]).PHP_EOL;
echo var_dump($deaths).PHP_EOL;

Upvotes: 0

Andrew Mast
Andrew Mast

Reputation: 309

To select stats from a multi-dimension array:

$searchName = 'total_kills';

$stat = $jsonforgame['playerstats']['stats'][array_search($searchName, array_column($jsonforgame['playerstats']['stats'], 'name'))];

Upvotes: 1

Related Questions