gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:35:51 26 4
gpt4 key购买 nike

我有以下数组,它们的键是 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);

}

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

最佳答案

我会这样做,我敢肯定这不是最优雅的,但它完成了工作。

// 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;

关于php - 获取数组中每第 n 个值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com