php - 如何计算运行总计?

标签 php mysql

我已经查看了 PHP 中的其他(许多已关闭的)运行总问题,但没有一个令人满意

这是我的查询

<?php
$query = "SELECT SUM(game_total) AS totalgames, 
                 SUM(goals) AS totalgoals, 
                 FROM player 
                 WHERE year between 2006 and 2013 
                 AND month between 1 and 12 
                 GROUP BY 
                 year,
                 month between 1 and 3,
                 month between 4 and 6,
                 month between 7 and 9,
                 month between 10 and 12
                 ORDER BY year ASC, month ASC";
$rquery = mysql_query($query) or die(mysql_error());

$show2 = '';

    while ($row = mysql_fetch_array($rquery)){

                $games = $row['totalgames'];
                $goals = $row['totalgoals'];

                $gpg = $games == 0 ? 0 : number_format($goals/$games,2);
}
    ?>

如果我回显完成循环的查询结果,我会得到以下结果

+---------+----------+-----------+
|  Goals  |   Games  |   GPG     |
+---------+----------+-----------+
|  8      |   15     |   0.53    |
+---------+----------+-----------+
|  2      |   12     |   0.17    |
+---------+----------+-----------+
|  2      |   12     |   0.17    |
+---------+----------+-----------+
|  13     |   21     |   0.62    |
+---------+----------+-----------+

等等等等

但是,我想通过以下方式计算正在运行的 GPG

Goals/Games=GPG
8/15=0.53
10/27=0.37 (8+2/15+12)=GPG
12/39=0.31 (10+2/27+12)=GPG
25/60=0.41 (12+13/39+21)=GPG

我想像这样回应它

0.53、0.37、0.31、0.41 等等

我该怎么做?

最佳答案

      $count = 0;
      while ($row = mysql_fetch_array($rquery)){

            $count++; 

            $games = (int)$row['totalgames'];
            $goals = (int)$row['totalgoals'];

            $totalGames = 0;
            $totalGoals = 0;

            $totalGames += $goalData['games'];
            $totalGoals += $goalData['goals'];

            echo $totalGoals/$totalGames;
            echo ($count === mysql_num_rows($rquery)-1) '' : ',';

}

我们开始,在迭代时运行总 GPG,用逗号分隔,而不创建额外的数组。这就是您要找的吗?

关于php - 如何计算运行总计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025134/

相关文章:

javascript - 使用 PHP 从数据库检索值、存储在输入文本和文本区域中、更改、将新值传递给数据库?

php - 数据库效率/结构问题

php - 使用 PHP 和页面安全性将记录添加到 MySQL

php - 如何在父主题 css 之后加载 wordpress 子主题 css

php - 使用 php-mysql 进行症状检查

mysql - 选择 SQL 之间的日期。其中日期的格式为 dd/mm/yyyy 并且是一个字符串

PHP 破坏了我的日期

php - 与 mvc/oop 相比,Spaghetti php 代码的性能和可扩展性?

php - 什么会更好 : click counter on mysql or on flat file?

mysql - SQL 中第 10 行 ENGINE=InnoDB'