如何在阵列中加总时间?

时间:2015-07-01 03:01:31

标签: php arrays function

我有一个阵列。我想在数组中总结所有时间,这样它将得到数组中所有时间的总和。 :

//print_r($chart_average);
Array ( [0] => 00:20:00 [1] => 00:03:45 [2])

如何在上面的数组中总结所有时间并显示如下所示的结果。如何计算所有数组?

总时间:00:23:45

在此之后我的回答是我的参考:

 foreach ($chart_average as $time) {
        list($hour, $minute, $second) = explode(':', $time);
        $all_seconds += $hour * 3600;
        $all_seconds += $minute * 60;
        $all_seconds += $second;

    }

   $total_minutes = floor($all_seconds/60);
   $seconds = $all_seconds % 60;
   $hours = floor($total_minutes / 60); 
   $minutes = $total_minutes % 60;

    // returns the time already formatted
    echo sprintf('%02d:%02d:%02d', $hours, $minutes,$seconds);

2 个答案:

答案 0 :(得分:1)

$times = array();

$times[] = "12:59";
$times[] = "0:58";
$times[] = "0:02";

// pass the array to the function
echo AddPlayTime($times);

function AddPlayTime($times) {

    // loop throught all the times
    foreach ($times as $time) {
        list($hour, $minute, $second) = explode(':', $time);
        $all_seconds += $hour * 3600;
        $all_seconds += $minute * 60; $all_seconds += $second;

    }


    $total_minutes = floor($all_seconds/60); $seconds = $all_seconds % 60;  $hours = floor($total_minutes / 60); $minutes = $total_minutes % 60;

    // returns the time already formatted
    return sprintf('%02d:%02d:%02d', $hours, $minutes,$seconds);
}

答案 1 :(得分:0)

有点难看,但它有效

$a = array('00:20:00', '00:03:45');
$h = $m = $s = 0;
foreach ($a as $time) {
    $time = new \DateTime($time);
    $h += $time->format('H');
    $m += $time->format('i');
    $s += $time->format('s');
}

$interval = new DateInterval("PT{$h}H{$m}M{$s}S");
echo $interval->format('%H:%I:%S');