Reputation: 6557
I currently have an array that is formatted like this array($time,$time,$time,$time,$time, $time)
where $time
is a string formatted like so m:ss:MM
where m
=minutes, s
=seconds and M
=milliseconds.
How would I do this?
I have a rough idea on how to do this which is:
convert each string into a timestamp
loop through array and calling an average function or do maths calculation (not sure how it works with unix timestamps).
Thanks for the help
Upvotes: 0
Views: 421
Reputation: 101
I believe there is no magic function in PHP for that. You would have to write something to sum up all the values and then divide by the number of elements. You can create a function for that by inputting two values and exploding the time, summing the values, validating (like if seconds is bigger than 60, you can turn it into an extra minute) and then you can do the same for dividing by the number of elements so you can finally have the average time.
The sum function would be something like this:
function sumTime($time1, $time2) {
$time1Exp = explode(':', $time1);
$time2Exp = explode(':', $time2);
$timeResult = array();
$extraMinutes = $extraSeconds = 0;
//sum milliseconds
$timeResult[2] = $time1Exp[2] + $time2Exp[2];
if($timeResult[2] >= 100) {
$extraSeconds = floor($timeResult[2] / 100);
$timeResult[2] -= $extraSeconds * 100;
}
$timeResult[1] = $time1Exp[1] + $time2Exp[1] + $extraSeconds;
if($timeResult[1] >= 60) {
$extraMinutes = floor($timeResult[1] / 60);
$timeResult[1] -= $extraMinutes * 100;
}
$timeResult[0] = $time1Exp[0] + $time2Exp[0] + $extraMinutes;
return implode(':', $timeResult);
}
Upvotes: 2