从PHP中的数组值计算平均增长 [英] Calculating the average increase from array values in PHP
问题描述
我需要计算数组值的平均增加量,并且制作了一个可以运行的小脚本,但是我想知道是否:
I need to calculate the average increase of array values, and I've made a little script which works, but I'd like to know if:
- 有一种更好,更有效的方法
- 在计算平均增长率时,我的逻辑是正确的
让我们说我有一个像这样的数组:
Lets say I have an array like so:
$array = array(5,10,15,10,0,15);
我们还可以想象每个数组项是1天,而该值是该天的某个计数器.我想计算柜台上的平均增/减.
Lets also imagine that each array item is 1 day, and the value is some counter for that day. I would like to calculate the average increase/decrease in the counter.
我所做的事情,遍历了数组,并更改了值,以使当前项=当前项-上一项,我将以何种方式留给数组,如下所示:
What I've done, is looped through the array, and altered the values so that the current item = current item - previous item, what way I'm left with an array which would look like so:
$array = array(5,5,-5,-10,15);
然后我按照正常值计算平均值,在此示例中,该平均值将使我每天平均增加2.
Then I calculate the average as per normal, which in this example would give me a 2 average increase on a daily basis.
此处的代码:
$array = array(5,10,15,10,0,15);
$count = count($array);
for($i=0;$i<$count;$i++) {
if($i==0) {
$value = $array[$i];
unset($array[$i]);
}
else {
$tmp = $array[$i];
$array[$i] -= $value;
$value = $tmp;
}
}
echo array_sum($array) / count($array);
这里的逻辑是正确的吗?有没有一种更有效的方式来做到这一点,也许没有循环?
Is the logic correct here, and is there a more efficient way of doing this, maybe without the loop?
先谢谢您了:)
更新了代码以排除第一个值
Updated code to account for excluding first value
推荐答案
这是怎么回事:
function moving_average($array) {
for ($i = 1; $i < sizeof($array); $i++) {
$result[] = $array[$i] - $array[$i-1];
}
return array_sum($result)/count($result);
}
这篇关于从PHP中的数组值计算平均增长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!