如何对数组时间求和 [英] how to sum the array time

查看:103
本文介绍了如何对数组时间求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组.我需要将所有出现次数的总时间长度相加.因此在下面的示例中,它将是00:04:03 + 00:06:03 = 00:10:06

I have an array like this. I need to add the total length of time in all the occurances of the array. so in the example below it will be 00:04:03 + 00:06:03 = 00:10:06

Array
(
  [4894] => Array
  (
    [0] => Array
    (
      [Informative] => Array
      (
        [id] => 109
      )     
      [jQuery] => Array
      (
        [length] => 00:04:03
        [alignment] => 8
      )
    )
    [1] => Array
    (
      [Informative] => Array
      (
        [id] => 110
      )     
      [jQuery] => Array
      (
        [length] => 00:06:03
        [alignment] => 8
      )
    )

如何在上述数组中增加长度,以使它仍然是一个时间并随着时间而增加.

how can I add length in the above array so that it still is a time and adds as time.

谢谢

推荐答案

$totalTimeSecs = 0;
foreach ($array as $l1) { // Loop outer array
  foreach ($l1 as $l2) { // Loop inner arrays
    if (isset($l2['jQuery']['length'])) { // Check this item has a length
      list($hours,$mins,$secs) = explode(':',$l2['jQuery']['length']); // Split into H:m:s
      $totalTimeSecs += (int) ltrim($secs,'0'); // Add seconds to total
      $totalTimeSecs += ((int) ltrim($mins,'0')) * 60; // Add minutes to total
      $totalTimeSecs += ((int) ltrim($hours,'0')) * 3600; // Add hours to total
    }
  }
}
echo "Total seconds: $totalTimeSecs<br />\n";

$hours = str_pad(floor($totalTimeSecs / 3600),2,'0',STR_PAD_LEFT);
$mins = str_pad(floor(($totalTimeSecs % 3600) / 60),2,'0',STR_PAD_LEFT);
$secs = str_pad($totalTimeSecs % 60,2,'0',STR_PAD_LEFT);
echo "Total time string: $hours:$mins:$secs";

看到它正常运行

这篇关于如何对数组时间求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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