2011-12-28 65 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