我在 MySql 数据库中有这张表:
运行此查询后:
SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC
结果表如下所示:
现在在 php 中,我尝试获取结果并遍历数组以确定每个教练属于哪个组并在排名中获得他的位置。因此我写了这个:
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM
.
.
.
more processing
} // end WHILE
为什么$response["scoresGroup"]
总是包含结果中的最后一个值?在这种情况下,这是123。我认为这是通过循环的第一次迭代,并且$response["scoresGroup"]
将保存第一个元素(474),在第二次迭代期间应该保存 382?我在这里做错了什么?我是否使用正确的函数来获取结果?还是我应该使用不同的循环来实现我的目标?我在这里先向您的帮助表示感谢。