在数组中每隔n个值获取平均值

3

我有一个包含 Unix 时间戳的数组,如何在新的数组中以每30秒为间隔获取平均值,其中键为 30 秒的时间间隔?

array (size=61)
1375398000 => int 350
1375398015 => int 357
1375398030 => int 354
1375398045 => int 353
1375398060 => int 361
// and so on...

期望的输出应该是:
1375398000 => int 353
1375398030 => int 354

我尝试了一些逻辑,使用key($array)来获取第一个值,但我无法确定这是否能够在foreach循环中正常工作。

迄今为止我的逻辑如下:

     while($a <= $end){

    $chartData[$a] = $array[$a] //do the average here - current($array) / count($array);

}

我不知道如何获取下一组要使用的键和值。

1
你能把你目前编写的逻辑发出来吗? - Fyntasia
为什么会有两个返回值?这是因为使用了键值分别为1375398000和1375398030的两组数据,分别计算它们的四舍五入平均值。其中第一组数据为1375398000 => int 350和1375398015 => int 357,其平均值为354;第二组数据为1375398030 => int 354和1375398045 => int 353,其平均值为354.5。我只是想要确保自己理解了你的逻辑。 - Mark Baker
没错,@MarkBaker。我需要缩短数组,以便数据每30秒更新一次,同时考虑到30秒之间的任何值。 - GSinghLDN
因此,可能每10秒钟就会有一次记录,但您仍然需要30秒钟的间隔平均值。 - Mark Baker
这是正确的@MarkBaker。 - GSinghLDN
1个回答

1

我会这样做,虽然不是最优雅的方法,但可以完成工作。

// Make sure the array is in the correct order
ksort($charData);

// This will be our new array
$tmp = array();

$interval = 30;

// Set the array's pointer to the first element
reset($charData); 
$last_timestamp = key($charData);

$total = 0;
$count = 0;

foreach ($charData as $timestamp => $value) {
    $total += $value;
    $count++;

    // If the current timestamp is newer 
    // than 30secs (or any interval set) we record the value
    if($timestamp - $last_timestamp >= $interval) {
        // Calculate the avg
        $tmp[$last_timestamp] = $total / $count;

        // Reset our helper vars
        $last_timestamp = $timestamp;
        $total = 0;
        $count = 0;
    }
}

$charData = $tmp;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接