循环以将变量添加到JSON数组

时间:2013-04-26 20:17:35

标签: php jquery mysql json

我想在我的JSON数组中添加一个新变量(得分)。数据库有每个成员收到的第一点数,第二点数和第三点数,我想计算每个成员的总得分,并显示所选团队的前十名。这是我必须将$ 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单选按钮,则会显示前十位蓝色成员的分数。

1 个答案:

答案 0 :(得分:-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);