EDIT I got it :) It's certainly not optimize but it works:
$db = json_decode( file_get_contents( $location ), true );
$users = $db['users'];
$scoreTeam1 = 0;
$scoreTeam2 = 0;
$scoreTeam3 = 0;
$scoreTeam4 = 0;
foreach ($users as $user) {
$team = $user['team'];
$userScore = $user['userScore'];
switch ($team) {
case 1:
$scoreTeam1 = $scoreTeam1 + $userScore;
break;
case 2:
$scoreTeam2 = $scoreTeam2 + $userScore;
break;
case 3:
$scoreTeam3 = $scoreTeam3 + $userScore;
break;
case 4:
$scoreTeam4 = $scoreTeam4 + $userScore;
break;
}
}
INITIAL PROBLEM I would like from the following json file to create a team ranking in php :
"users": {
"uniqueID": {
"team": 1,
"userScore": 2500,
}, "uniqueID": {
"team": 2,
"userScore": 1235,
}, "uniqueID": {
"team": 3,
"userScore": 6582,
}, "uniqueID": {
"team": 4,
"userScore": 1200,
}, "uniqueID": {
"team": 1,
"userScore": 9875,
}, "uniqueID": {
"team": 2,
"userScore": 500,
}, "uniqueID": {
"team": 3,
"userScore": 12,
}, "uniqueID": {
"team": 4,
"userScore": 695,
}, "uniqueID": {
"team": 1,
"userScore": 332,
}, etc.
}
I have 4 teams, I suppose I need to create 4 variables :
$scoreTeam1
$scoreTeam2
$scoreTeam3
$scoreTeam4
Could you help me to translate this : for each uniqueID if team == 1 scoreTeam1 +=userScore, else if team == 2 scoreTeam2 += userScore, etc...
Any help is more than welcome :) Best regards.
You can achieve what you want with array_reduce function:
$result = array_reduce($db['users'], function($carry, $team){
if (isset($carry[$team['team']]) ) {
$carry[$team['team']] = $carry[$team['team']] + $team['userScore'];
} else {
$carry[$team['team']] = $team['userScore'];
}
return $carry;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.