PHP的多个持续时间相加以获得总持续时间 [英] php addition of multiple durations to get total duration

查看:186
本文介绍了PHP的多个持续时间相加以获得总持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用php在数据库表中的开始时间和结束时间,我正在计算开始时间和结束时间之间的差,以获得任务的总持续时间.

start time and end time in a database table using php and I am calculating the difference between the start time and end time to get the total duration total of a task.

我正在使用以下方法:

 foreach ($task->timers as $time ) {
    $start_date = new DateTime($time->date.' '.$time->start_time);
    $end_date = new DateTime($time->date.' '.$time->end_time);
    $times[] = date_diff($end_date, $start_date);
   }

然后我如下遍历上面的数组;

I then loop through the array above as follows;

  foreach ($times as $timer) {
        $minutes = strlen($timer->i);
        if($minutes == 1) {
            $minutes = '0'.$timer->i;
        } else {
            $minutes = $timer->i;
        }
        $o[] = $timer->h.':'.$minutes.':'.$timer->s;
    }

然后我得到一个如下数组;

I then get an array as follows;

array(2) { [0]=> string(7) "0:54:17" [1]=> string(7) "0:01:26" }

现在,我想将这两个值加在一起以获得总持续时间,我正尝试按以下步骤进行操作;

Now I want to add those two values together to get the total duration and I'm attempting to do this as follows;

    $totalTime = array_sum($o);

无论如何,它返回为:

int(0);

有什么想法可以计算两个工期的总工时吗?

Any ideas how I can calculate the total duration of two durations??

推荐答案

不幸的是,array_sum不适用于字符串,仅适用于数值(因为PHP显然不知道如何对字符串进行数学运算).您可以像这样简单地加起来:

Unfortunately array_sum does not work on strings, only on numerical values (because PHP has no clue how to do math with strings obviously). You could simply add up like this:

$hrs = 0;
$mins = 0;
$secs = 0;

foreach ($o as $time) {
    // Let's take the string apart into separate hours, minutes and seconds
    list($hours, $minutes, $seconds) = explode(':', $time);

    $hrs += (int) $hours;
    $mins += (int) $minutes;
    $secs += (int) $seconds;

    // Convert each 60 minutes to an hour
    if ($mins >= 60) {
        $hrs++;
        $mins -= 60;
    }

    // Convert each 60 seconds to a minute
    if ($secs >= 60) {
        $mins++;
        $secs -= 60;
    }
}

现在,您将拥有值为55的$mins和值为43的$secs. 您可以再次以任何所需的格式打印它们,例如:

Now you will have $mins with a value of 55 and $secs with a value of 43. You can print them in any desired format again, like:

echo sprintf('%d:%d:%d', $hrs, $mins, $secs);

这将导致0:55:43.

这篇关于PHP的多个持续时间相加以获得总持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆