Does PHP have a function for aggregating time values from an array?

僤鯓⒐⒋嵵緔 提交于 2019-12-02 22:05:55

问题


So my query is like this:

SELECT TIMEDIFF('24:00:00',(TIMEDIFF('22:00:00',TIME(end)))) AS time
FROM sworkingtime
WHERE user='magdalena' AND type='work' AND start BETWEEN '2014-03-01' AND '2014-03-28' AND (HOUR(`end`) > 22 OR HOUR(`end`) < 4)
AND completed=1

My query returns this:

02:02:36
03:17:24
03:07:03
02:24:17
03:14:09

Is there a way to modify this query to return only SUM of this fields, so one field only?

Thank you


回答1:


No, there's no special sum function in this case - especially paying attention that you need some time summation, not just simple operation.

To do that, you can apply callback on your array. Very powerful function for that is array_reduce(). For working with date intervals you can use DateTime API, like:

$data = [
  ['time'=>'02:02:36'],
  ['time'=>'03:17:24'],
  ['time'=>'03:07:03']
];


$time = array_reduce($data, function($c, $x)
{
   $x = explode(':', $x['time']);
   $c = explode(':', $c);
   return (new DateTime('2000-01-01'))
      ->add(new DateInterval('PT'.(int)$c[0].'H'.(int)$c[1].'M'.(int)$c[2].'S'))
      ->add(new DateInterval('PT'.(int)$x[0].'H'.(int)$x[1].'M'.(int)$x[2].'S'))
      ->format('H:i:s');
}, '00:00:00');

-this will result in "08:27:03" as string. But if you want to get object, remove format() call.




回答2:


You can iterate the array and use this function to sum Sum time php



来源:https://stackoverflow.com/questions/22372199/does-php-have-a-function-for-aggregating-time-values-from-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!