Reputation: 95
I'm training myself (JSON and PHP) and I have a problem I have Json decode look like this :
"playerstats": {
"steamID": "75068112",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 2314497
},
{
"name": "total_deaths",
"value": 1811387
},
And to parse into php i do :
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['playerstats']['stats'][1]['name']
And it works but the problem is when i change the id to get stats, the order of the array isn't the same :/ So i can't use [2] or any else number to get data.
I post here to know how could'i get stats using the attribute name of each array ('total_kills'
for example) instead of [1]..[2]..
thanks for all your support
Upvotes: 0
Views: 117
Reputation: 10971
Another way to do something with all objects in an array is to use the array_map()
function, which takes another function as one of its arguments. Using this whenever you can will force you to adhere to good programming practices, because the passed in function cannot modify values outside of the array and arguments passed in via use
.
Upvotes: 0
Reputation: 12085
Use foreach
and use if condition to check the name is 'total_kills'
is true then store it into new array like this .
<?php
$json = json_decode($content, true);
$new_array =array();
$i=0;
foreach($json['playerstats']['stats'] as $row )
{
if($row['name']=='total_kills')
{
$new_array[]=array($row['name']=>$row['value']);
}
if($i<10)
{
break;
}
$i++
}
print_r($new_array);
?>
Upvotes: 1
Reputation: 1560
What you're looking for is a way to loop over the array. In PHP you can do the following;
$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json["playerstats"]["stats"] as $stat){
if($stat["name"] == "total_kills"){
echo "total kills: ".$stat["value"];
}
elseif($stat["name"] == "total_deaths"){
// ...
}
// etc... continue to select all parameters you would like
}
This will allow you to get the value
for each stat with name
using the if else statement.
Upvotes: 0
Reputation:
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['playerstats']['stats'] as $row )
{
echo $row['name'];
echo $row['value'];
}
Upvotes: 0