唯一的ID用户团队排名php / json

时间:2019-02-23 20:18:51

标签: php json

编辑 我知道了 :) 它当然不是最优化的,但是可以工作:

$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;
    }
}

最初的问题 我想从以下json文件在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.
}

我有4个团队,我想我需要创建4个变量:

  1. $scoreTeam1
  2. $scoreTeam2
  3. $scoreTeam3
  4. $scoreTeam4

您能帮我翻译一下吗: 对于每个唯一ID 如果团队== 1得分团队1 + =用户得分, 否则,如果team == 2 scoreTeam2 + = userScore, 等等...

任何帮助都非常值得欢迎:) 最好的问候。

1 个答案:

答案 0 :(得分:0)

您可以使用array_reduce函数来实现所需的目标:

$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;
});