我正在使用以下示例代码来计算两个不同时间值的总和。现在,我想获得N个时间值的总和。

// numbers for testing
$o="12:59";
$p="0:58";

// display for testing
echo "$o<br />";
echo "$p<br />";
echo AddPlayTime($o,$p);

// FUNCTION - ADD HOURS and MINUTES
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {
  $old=explode(":",$oldPlayTime);
  $play=explode(":",$PlayTimeToAdd);

  $hours=$old[0]+$play[0];
  $minutes=$old[1]+$play[1];

  if($minutes > 59){
    $minutes=$minutes-60;
    $hours++;
  }

  if($minutes < 10){
    $minutes = "0".$minutes;
  }

  if($minutes == 0){
    $minutes = "00";
  }

  $sum=$hours.":".$minutes;
  return $sum;
}

最佳答案

这应该可以满足您的需求:
$times是时间数组,您可以添加所需的时间

$times = array();

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

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

function AddPlayTime($times) {
    $minutes = 0; //declare minutes either it gives Notice: Undefined variable
    // loop throught all the times
    foreach ($times as $time) {
        list($hour, $minute) = explode(':', $time);
        $minutes += $hour * 60;
        $minutes += $minute;
    }

    $hours = floor($minutes / 60);
    $minutes -= $hours * 60;

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

编辑

我用正确的变量名称编辑了代码。现在更正确了。

希望这可以帮助 :-)

关于php - 如何求和N次(HH :MM Format)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22681725/

10-12 04:00