我有一个在线游戏的评分系统,它基于人们从玩家列表中创建团队。
输入玩家得分字段后,下面的脚本应根据预定义的点数乘数计算得分并更新3个表格中的数据
在这里简单了解我的数据库结构
玩家表
- ID
- score1
- score2
- 总
得分表
- ID
- playerid
- score1
- score2
- 总
- 时间
团队表
- ID
- 用户ID
- P1
- P2
- B3
- B4
- 得分1(这是所有4名球员得分1的总和)
- 得分2(这是所有4名球员得分2的总和)
- 总计(这是所有4名球员的所有计算得分的总和)
- 时间
问题
令人惊讶的是,第1步和第2步工作正常,分数被添加并且玩家被正确添加但是当我进入步骤3时,一些团队得到正确更新,其中一些团队没有用正确的分数更新
我的代码
//predefined points multiplier
define("points1", 7);
define("points2", 8);
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$score1= $_POST['score1'];
$score2 = $_POST['score2'];
foreach($id as $key=>$player){
//calculate the total points based on their predefined multipliers
$totalpoints = 0;
$totalpoints += $score1[$key] * points1;
$totalpoints += $score2[$key] * points2;
//update player table
#send a request to api to update this player data
//add scores
#send a request to api to add the new scores to the score table
//update teams (updates the teams for users)
$raw = [
'id' => $id,
'score1' => $score1[$key],
'score2' => $score2[$key],
'total' => $totalpoints
];
$data = http_build_query ($raw);
$result = file_get_contents(
BASE_URL . 'update',
false,
stream_context_create(array(
PROTOCOL => array(
'method' => 'PUT',
'header' => array(
'Content-Length: ' . strlen($data),
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
),
'content' => $data
)
))
);
$response = json_decode($result, false);
}//end foreach
echo $response->notice->message;
}
答案 0 :(得分:1)
您现在$totalpoints
的方式永远是0
。
玩家得到正确更新,因为得分的值是在foreach循环中设置的
$totalpoints = 0;
$totalpoints += $score1[$key] * points1; // <- $key does not exist result will be 0
$totalpoints += $score2[$key] * points2; // <- $key does not exist result will be 0
foreach($id as $key=>$player){
$raw = [
'id' => $id,
'score1' => $score1[$key], // <- $key has a value
'score2' => $score2[$key], // <- $key has a value
'total' => $totalpoints // <- result is always 0
];
}
尝试将其更改为
foreach($id as $key=>$player){
$totalpoints = 0;
$totalpoints += $score1[$key] * points1; // <- $key has a value
$totalpoints += $score2[$key] * points2; // <- $key has a value
$raw = [
'id' => $id,
'score1' => $score1[$key], // <- $key has a value
'score2' => $score2[$key], // <- $key has a value
'total' => $totalpoints // now does have a chance to be other then just 0
];
}