问题
I wanted to get an average hours but I'm having problems because if I use DateTime.add() object for adding time when it exceeds 24 hours it converts time to "day". Basically I just want to get the average of these times in "hours". Please help.
$time = array();
$time[] = '00:00:58';
$time[] = '00:45:08';
$time[] = '00:00:49';
$time[] = '00:11:26';
$time[] = '02:34:39';
$time[] = '02:18:24';
$time[] = '02:24:11';
$time[] = '01:23:19';
$time[] = '00:27:30';
$time[] = '02:14:50';
$time[] = '00:48:47';
$time[] = '02:19:52';
$time[] = '02:04:29';
$time[] = '01:08:46';
$time[] = '00:06:57';
$time[] = '00:35:31';
$time[] = '02:16:59';
$time[] = '02:23:33';
$time[] = '02:36:30';
$time[] = '02:11:47';
$time[] = '02:40:44';
$time[] = '02:03:42';
$time[] = '01:45:50';
回答1:
Try this,
$total_time=0;
foreach($time as $t){
$total_time+=strtotime($t)-1373241600;
}
So $total_time will be an integer number and you can divide it with 3600 and with count($time) to get average hour :)
$average_time = ($total_time/count($time))/3600;
回答2:
Try this (note closures are available in 5.3+):
$timestamps = array_map(function($a){return strtotime($a);}, $time);
$avg = (array_sum($timestamps)/count($timestamps))/3600;
回答3:
If you do not want to rely on timezone settings, subtract timestamp for current day or annoyed with sluggishness of strtotime, use simple math instead:
$timestamps = array_map(function($item){
list($h, $m, $s) = explode(':', $item);
return intval($h) * 3600 + intval($m) * 60 + intval($s);
}, $time);
$avg = ceil(array_sum($timestamps)/count($timestamps));
echo gmdate('H:i:s', $avg);
来源:https://stackoverflow.com/questions/17534074/time-average-in-hours