2011-12-28 45 views
-4

我有一个这样的数组。我需要在数组的所有出现时间内添加总时间。所以在它下面的例子将是0时04分03秒+ 0时06分03秒=零点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 
    ) 
    ) 

如何添加长度以上阵列中,使得它仍然是一个时间,并增加了随着时间的。

感谢

+0

你尝试过什么?它应该是一个简单的问题,解析它并转换为秒然后格式化。 – jprofitt 2011-12-28 01:18:05

回答

2
$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"; 

See it working

0
  1. 为了找到sum of seconds,迭代通过您的阵列和从所述时间为每个条目即3600 *小时+ 60 *分钟+秒计算total seconds
  2. 转换sum of seconds时间表示:
sumSecs = ... 
hour = sumSecs/3600 
min = (sumSecs mod 3600)/60 
sec = sumSecs mod 60