duangewu5234 2013-11-15 14:42
浏览 136
已采纳

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

I have the following array with they keys being unix timestamps, how can I get the average vlaue for example at an interval of every 30 seconds in a new array with the key being the 30 second interval?

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

The desired output should be

1375398000 => int 353
1375398030 => int 354

I have tried some logic with using key($array) to get the first value but I cant figure out if this is working correctly inside a foreach loop.

My logic so far

     while($a <= $end){

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

}

I dont know how to get the next set of the keys and values to be used

  • 写回答

1条回答 默认 最新

  • dongzang5815 2013-11-15 15:40
    关注

    I'd do this, I'm sure this is not the most elegant, but it gets the job done.

    // 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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)