如何对时间数组求和?的PHP

时间:2019-03-29 08:42:11

标签: php arrays

如何获取多维数组的总和?

我的阵列返回

array(25) {
  [0]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "01:30:00"
  }
  [1]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:30:00"
  }
 [2]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:30:00"
  }
  [3]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:15:00"
  }
  [4]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:15:00"
  }

如何动态获取这些值的总和?预期的输出应该是一个变量,它将所有这些时间字符串加在一起

1 个答案:

答案 0 :(得分:0)

最好的方法是将时间转换为秒,然后将其添加,然后再次将其转换为可读格式。如下所示:

function sum_the_time($times) {
    $seconds = 0;
    foreach ($times as $time) {
        list($hour, $minute, $second) = explode(':', $time['time_in_minutes']);
        $seconds += $hour*3600;
        $seconds += $minute*60;
        $seconds += $second;
    }

    $hours = floor($seconds/3600);
    $seconds -= $hours*3600;
    $minutes  = floor($seconds/60);
    $seconds -= $minutes*60;
    if ($seconds < 9) {
        $seconds = "0" . $seconds;
    }
    if ($minutes < 9) {
        $minutes = "0" . $minutes;
    }
    if($hours < 9) {
        $hours = "0" . $hours;
    }
    return "{$hours}:{$minutes}:{$seconds}";
}

在上面的示例中,$time是一个数组。