3

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

5
  • 1
    Could you post the logic you've programmed so far? Commented Nov 15, 2013 at 14:44
  • Why those two returns? Is that the rounded average of 1375398000 => int 350 and 1375398015 => int 357 with the key of 1375398000, and the rounded average of 1375398030 => int 354 and 1375398045 => int 353 with a key of 1375398030? Just trying to get the logic that you want straight in my head Commented Nov 15, 2013 at 14:51
  • thats correct @MarkBaker, I need to shorten the array so the data is at every 30 seconds whilst taking into account any values between the 30 seconds. Commented Nov 15, 2013 at 14:54
  • So there could be entries every 10 seconds, but you still need 30 second interval averages Commented Nov 15, 2013 at 14:59
  • That's correct @MarkBaker Commented Nov 15, 2013 at 15:00

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.