2013-04-26 80 views
-3

我想向我的JSON數組添加新變量(分數)。數據庫有每個成員的第一點,第二點和第三點的數量,我想計算每個成員的總分,並顯示所選團隊的前十名。這是我必須將$分數添加到JSON的代碼,但它只會將其添加到數組的末尾,而不是每個成員。循環通過向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單選按鈕,前十名藍色會員將會顯示他們的分數。

+2

你不要用 「JSON數組」 工作。沒有這樣的事。有一個JSON字符串。您處理NATIVE數據結構,然後在完成後使用json_encode/json_decode轉換爲/從json。 – 2013-04-26 20:21:27

+0

@MarcB我再次使用json_encode – Raynor 2013-04-26 20:30:35

回答

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

UPDATE:

$result = $res->fetchAll(); 
foreach($result as $key => $entry) 
    $result[$key]['score'] = $score; 
echo json_encode($result); 
+0

所有這些都是{「score」:0} – Raynor 2013-04-26 20:24:18

+0

@Raynor'fetchAll'是否返回正確的結果? – zavg 2013-04-26 20:26:00

+0

fetchAll帶回所有正確的數據 – Raynor 2013-04-26 20:28:42