获取数组中每第n个值的平均值

时间:2013-11-15 14:42:36

标签: php arrays math operators logic

我有以下数组,其中键是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

我尝试使用键($ array)来获取第一个值,但我无法弄清楚它是否在foreach循环中正常工作。

到目前为止我的逻辑

     while($a <= $end){

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

}

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

1 个答案:

答案 0 :(得分: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;