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