0

I'm calculating daily averages of $spent in a table using mysql. In php, I'd like to average all those daily averages into 1 average daily average. Eventually, I'd like to do this for multiple tables and graph the final averages in highcharts. Right now, I can't get php to average the results of my query. I am connecting to my database, but just not showing it in the code. See code below:

<?php

    function array_average($arr){
        $sum = array_sum($arr);
        $num = sizeof($arr);
        echo $sum/$num;
    }

    $sth = mysql_query("SELECT round((sum(d_power),2) as $perton FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 3 month) and curdate() GROUP BY Day(timestamp) ORDER BY Timestamp");
    $rows = array();
    while($r = mysql_fetch_array($sth)) {
        $rows['data'][] = $r['$perton'];
    }

    echo array_average($rows);

    mysql_close($con);
?>
4

3 回答 3

2

为什么不在 SQL 中进行计算?

select avg($perton) as $perton
from (SELECT round(sum(d_power), 2) as $perton
      FROM pheom.pheom_gb
      WHERE timestamp between subdate(curdate(), interval 3 month) and curdate()
      GROUP BY Day(timestamp)
     ) t;
于 2013-08-16T18:13:19.373 回答
0

$perton来自哪里?您的查询是用双引号引起来的,这意味着该变量正在被扩展,但您的数组访问是用单引号引起来的,所以它不是。

如果$perton未定义,那么我相信您的查询将被评估为:

SELECT round((sum(d_power),2) as FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 3 month) and curdate() GROUP BY Day(timestamp) ORDER BY Timestamp

这是一个语法错误。

此外,我认为不适array_sum用于多维数组。我会尝试:

echo array_average( $rows['data'] );
于 2013-08-16T17:32:10.237 回答
0

这与 PHP 或任何其他脚本语言无关。这正是您应该始终尝试在数据库查询中解决的问题 - 与将所有数据传递给脚本相比,您将获得更简洁的解决方案和更好的性能,只是为了进行您可以通过单个查询获得的计算第一名。Gordon Linoff 给出的答案是正确的。

于 2013-08-21T17:46:08.683 回答