I'm trying to get the player
with the highest rating
from the following JSON object. I have two teams home
and away
and I want to compare all ratings from all players and return the highest rating
value and the name
of the player.
{
"lineup": {
"home": {
"starters": [{
"name": "Andreas",
"statistics": {
"rating": 6.38
}
},
{
"name": "Carlos",
"statistics": {
"rating": 6.87
}
}
]
},
"away": {
"starters": [{
"name": "Felix",
"statistics": {
"rating": 7.20
}
},
{
"name": "Daniel",
"statistics": {
"rating": 4.87
}
}
]
}
}
}
Keep in mind that my JSON includes 30 players
with their ratings
and not 4
What I've tried so far.
Attempt #1:
I've tried to get the max
from home
and away
team and then compare these two values and get the highest, for some reason it doesn't return the maximum value on each team. Ex for team home
returns the player
with the rating 6.38
instead the other one.
//Home
$max = max($decode_one['lineup']['home']['starters']);
$finalVal = $max['statistics']['rating'];
//Away
$max1 = max($decode_one['lineup']['away']['starters']);
$finalVal1 = $max1['statistics']['rating'];
Attempt #2:
Here I've added the ratings inside to a new array and then with a loop got the max value from the array. The 2 issues that I have is first the JSON includes 30 players, 15 from home
and 15 away
for some reason it puts only the 15 players from home
and not from both. I think that is because the keys from each team are the same (0-14) and the other issue I want as well to return name
of the selected player
.
$result = array();
foreach ($decode_one['lineup'] as $homeOrAway) {
foreach ($homeOrAway as $startersOrSubs) {
foreach ($startersOrSubs as $key => $value) {
$result[$key['rating']][] = $value['statistics']['rating'];
}
}
}
foreach ($result as $key => $maxValue) {
echo "{$key}: " . max($maxValue) . "\n";
}
Any ideas?
Thank you