-3

我想在我的 JSON 数组中添加一个新变量(分数)。数据库中有每个成员获得的第 1 分、第 2 分和第 3 分的数量,我想计算每个成员的总分并显示所选团队的前十名。这是我必须将 $score 添加到 JSON 的代码,但它只将它添加到数组的末尾,而不是每个成员。

$result[] = $res->fetchAll();  
$result[] = array('score' => $score);  
echo json_encode($result);

我有一个 if 语句,它取决于用户按下的单选按钮。这就是我计算分数的方式:

if($redTeam == true){
$score = (($no_first_points + $no_scnd_points + $no_third_points)/$redMembers);
}

else if($blueTeam == true){
$score = (($no_first_points + $no_scnd_points + $no_third_points)/$blueMembers);
}

如果我当前回显 JSON 数组,我会得到:

{
    "no_first_points": "10",
    "no_scnd_points": "25",
    "no_third_points": "15",
    "redMembers": "125",
    "blueMembers": "1‌​25",
    "team_name": "Blue"
}, {
    "no_first_points": "20",
    "no_scnd_points": "17",
    "no_third_points": "27",
    "redMembers": "125",
    "blueMembers": "1‌​25",
    "team_name": "Red"
}, {
    "score": "40"
}

但是我希望每个团队在同一个数组中都有正确的分数,如下所示:

{
    "no_first_points": "10",
    "no_scnd_points": "25",
    "no_third_points": "15",
    "members": "125",
    "blueMembers": "1‌​25",
    "team_name": "Tigers",
    "score": "40"
}, {
    "no_first_points": "20",
    "no_scnd_points": "17",
    "no_third_points": "27",
    "redMembers": "125",
    "blueMembers": "1‌​25",
    "team_name": "Pumas",
    "score": "45"
}

我总共有来自两个团队的 200 名成员需要分配一个分数,然后我想显示所选团队的前十名。因此,如果选择了 Blue Team 单选按钮,则会显示前十名蓝色成员及其分数。

4

1 回答 1

-1
$result = $res->fetchAll();  
$result['score'] = $score;  
echo json_encode($result);

更新:

$result = $res->fetchAll();  
foreach($result as $key => $entry)
    $result[$key]['score'] = $score;
echo json_encode($result);
于 2013-04-26T20:20:14.127 回答