Mats Bakken Mats Bakken - 4 years ago 150
PHP Question

Grabbing unnamed(?) data from json with PHP

I'm having a bit of trouble here...

I'm trying to grab some values from a json file here, and it can be formatted here.

The json file looks like this:

"type": "success",
"message": "OK",
"data": {
"mainWeaponStats": [
"category": "Machine guns",
"timeEquipped": 3507,
"startedWith": null,
"code": "mgRPK",
"headshots": 18,
"name": "RPK",
"kills": 100,
"deaths": null,
"category": "Handheld weapons",
"timeEquipped": 5452,
"startedWith": null,
"code": "wahUGL",
"headshots": 1,
"name": "Underslung Launcher",
"kills": 108,
"deaths": null,
"category": "Sniper rifles",
"timeEquipped": 307,
"startedWith": null,
"code": "srMK11",
"headshots": 0,
"name": "MK11",
"kills": 2,
"deaths": null,

And so on.

I want to grab the kills of one of these items. Meaning I want to give a parameter like "Underslung Launcher" and return with 108.
In this case, the "Underslung Launcher".
I'm looking for a code like this:

$gamemode = $decode['data']['topStats']['mapMode'];

But if anyone know a better way, please, tell me.
Since the items in the list doesn't have a "name", unlike "data" & "mainWeaponStats", I can't really figure out how to do this.

This is the relevant code so far:

$weaponstats = "" . $bf3id . "/1/";
$content = file_get_contents($weaponstats);
$decode = json_decode($content, true);

$mainweaponstats = $decode['data']['mainWeaponStats'];

As you can see, I'm having a hard time learning Json.
I'm trying to read up on it, but as of now, I can't figure this out.

I don't really know how I'm going to do it, as the values I'm trying to find are within the same group.

Answer Source
$mainweaponstats = $decode['data']['mainWeaponStats'];

This is an array of objects (well arrays because you passed ,true to json_decode). Just loop through this and find what you want.

$search = 'Underslung Launcher';
$kills = 0;
foreach($mainweaponstats as $w){
    if($w['name'] === $search){
        $kills = $w['kills'];
echo $kills;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download