在PHP中计算表的深度总和平均值

时间:2015-11-06 08:48:29

标签: php mysql

我有一个PHP代码来计算显示登录持续时间和计数。 但是我希望在表格结束时我想计算每列末尾的总持续时间和登录计数。 在漫游结束时,我想计算平均登录持续时间和平均登录次数,即总持续时间/项目数。但是不能这样做。 你能给我一个暗示吗?

    $result = mysql_query("SELECT connection_log.user, `count(*) as         'connection_count', sum(TIMESTAMPDIFF(MINUTE,connection_log.logondate, connection_log.logoffdate)) as `connection_time`
FROM connection_log 
INNER JOIN users ON connection_log.user=users.user 
WHERE users.groups 
LIKE '%cpg_sirket_dyo%' and connection_log.logondate>='2015-09-01 00:00:00' and connection_log.logoffdate<'2015-10-01 00:00:00' 
group by connection_log.user 
order by connection_count desc",$con);
echo '<table width="80%" border="1" align="center" cellspacing="0" cellpadding="0">';
echo "  <tr>
    <th> Row number </th>
    <th> Username </th>
    <th> Total login count </th>
    <th> Total login duration(min.) </th>
    </tr> ";
$counter = 1;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) 
{
echo "  <tr>
        <td> ". $counter ." </td>
        <td> ". $row['user'] . "</td>
        <td> ". $row['connection_count'] ." </td>
        <td> ". $row['connection_time']  ." </td>
        </tr> ";
$counter++;
}

//SUM CALCULATION
//NEED HERE!
//
echo "</table><br>\n";
echo $icounter. " Items<br>\n";

mysql_close($con);

1 个答案:

答案 0 :(得分:3)

将所有信息存储在数组中并计算最终的平均值:

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) 
{
echo "  <tr>
        <td> ". $counter ." </td>
        <td> ". $row['user'] . "</td>
        <td> ". $row['connection_count'] ." </td>
        <td> ". $row['connection_time']  ." </td>
        </tr> ";
$connection_count[] = $row['connection_count'];
$connection_time[] = $row['connection_time'];

$counter++;

}

$meanCount = array_sum($connection_count)/count($connection_count);
$meanTime = array_sum($connection_time)/count($connection_time);

// do what ever you like with it

echo "</table><br>\n";

希望这有帮助