[英]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 . 我正在尝试从此处的json文件中获取一些值,并且可以在此处将其格式化。
The json file looks like this: json文件如下所示:
{
"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". 意思是我想给一个像“ Underslung Launcher”的参数并返回108。在这种情况下,就是“ 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. 由于列表中的项目没有“名称”,因此与“数据”和“ mainWeaponStats”不同,我无法真正弄清楚该如何做。
Edit: This is the relevant code so far: 编辑:这是到目前为止的相关代码:
$weaponstats = "http://battlelog.battlefield.com/bf3/weaponsPopulateStats/" . $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. 如您所见,我在学习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. 我真的不知道该怎么做,因为我要查找的值在同一组中。
$mainweaponstats = $decode['data']['mainWeaponStats'];
This is an array of objects (well arrays because you passed ,true
to json_decode
). 这是一个对象数组(数组,因为您将,true
传递给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'];
break;
}
}
echo $kills;
<?
$name = "Underslung Launcher";
$json = file_get_contents("json.php");
$dec = array();
$dec = json_decode($json,true);
$datas = $dec['data']['mainWeaponStats'];
foreach($datas as $data)
{
if($data['name']==$name) {
echo $data['kills'];
break;
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.