首先,我有点困惑的是,对于以下问题,最好的实现方式是什么,即纯粹可以只用mysql而不改变表,或者我需要PHP和mysql的组合,就像我现在所做的那样。 请在阅读时牢记这一点:
问题信息
Pickem游戏的工作原理如下:
1-在锦标赛中显示所有比赛/赛程。
2-用户进入他认为将赢得每个夹具的球队。
从表schedule
中提取灯具,用户结果记录在表picks
请记住
每轮比赛可以有多场比赛(1到30场比赛之间)
我正在尝试做什么/问题
我正在尝试计算选择team1
获胜的用户数以及在锦标赛中为特定回合选择team2
的用户数。
示例
曼彻斯特联队:7位用户选择了| 阿森纳3:用户选择了
MYSQL表格
计算后上表的预期输出
所以对于Super Rugby第一轮,它应该如下:
gameID 1
记录了4个选秀权,2个用户选择了Jaquares 1个用户选择Stormers(现在忽略抽签)gameID 2
记录了4个选秀权,4个用户选择了Sharks,0个用户选择了狮子会我的代码
function calcStats($tournament, $week)
{
global $db;
//GET ALL GAMES IN TOURNAMENT ROUND
$sql = 'SELECT * FROMpicks
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum ORDER BY gameID';
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tournament', $tournament);
$stmnt->bindValue(':weekNum', $week);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
$picks = $stmnt->fetchAll();
return $picks;
}
return false;
}
test.php的
$picks = calcStats('Super Rugby', '1');
foreach($picks as $index=> $pick) {
if($pick['gameID'] !== $newGameID){
?>
<h1><?php echo $pick['gameID']?></h1>
<?php
//reset counter on new match
$team1 = 0;
$team2 = 0;
}
if($pick['picked'] === $newPick){
//gameID is passed as arrayKey to map array index to game ID
//team name
$team1[$pick['picked']];
//number times selected
$team1Selections[$pick['gameID']] = $team1++;
}
else if($pick['picked'] !== $newPick){
///gameID is passed as arrayKey to map array index to game ID
//team name
$team2[$pick['picked']];
$team2Selections[$pick['gameID']] = $team2++;
}
$newPick = $pick['picked'];
$newGameID = $pick['gameID'];
}
PRINT_R()
功能$picks = calcStats('Super Rugby', '1')
我的问题很有道理,如果您需要任何其他信息,请在下面评论,感谢您抽出宝贵时间阅读。
答案 0 :(得分:1)
似乎你在PHP中做得太多,可以在MySQL中轻松完成;请考虑以下查询:
SELECT gameID, team, COUNT(*) AS number_of_picks
FROM picks
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum
GROUP BY gameID, team
ORDER BY gameID, team
根据您的示例,这将给出以下结果:
1 | Jaquares | 2
1 | Stormers | 1
1 | Draw | 1
2 | Sharks | 4
然后,在PHP中,您对游戏进行分组:
$result = array();
foreach ($stmnt->fetchAll() as $row) {
$result[$row['gameID']][] = $row;
}
return $result;
您的数组将包含以下内容:
[
'1' => [
[
'gameID' => 1,
'team' => 'Jaquares',
'number_of_picks' => 2,
],
'gameID' => 1,
'team' => 'Stormers',
'number_of_picks' => 1,
],
...