0

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 :)

3 Answers 3

1

To select stats from a multi-dimension array:

$searchName = 'total_kills';

$stat = $jsonforgame['playerstats']['stats'][array_search($searchName, array_column($jsonforgame['playerstats']['stats'], 'name'))];
Sign up to request clarification or add additional context in comments.

Comments

0

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;

1 Comment

EDIT: using question's array name.
0

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'];

3 Comments

He isn't asking how to structure the stats, just how to access them.
And this structure makes them easier to access. If restructuring the array is an option, this is much easier and more readable.
This would be the ideal way but I have no influence over the array structure.