2

晚上好

我在这里有个问题。我有两个数组:$duration_c[$k][$s]。一切正常

$duration_c[0][0]="19:30:00";
$duration_c[0][1]="00:10:00";

$duration_c[1][0]="00:30:00";
$duration_c[1][1]="00:20:00";

比总和

$times=$duration_c[$k][$s];
function sum_the_time($times) {

  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
 }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  // return "{$hours}:{$minutes}:{$seconds}";
  return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
} 
echo sum_the_time($times);

$duration_c[0][0]+$duration_c[0][1] 和 $duration_c[1][0]+$duration_c[1][1] 如何求和,如何打印?为 foreach() 提供了错误无效参数

4

3 回答 3

1

您只向 sum_the_time 函数发送一个值,因为$times=$duration_c[$k][$s]; $times 只有一个值,您可以打印并通过这样编写检查函数的值

$times=$duration_c[$k][$s];
echo $times;

采用

$times=$duration_c[$k];

这样您就可以将数组发送到您的函数并且 foreach 不会给您错误

$times=$duration_c[$k]; // contains array of times
function sum_the_time($times) {

  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
 }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  // return "{$hours}:{$minutes}:{$seconds}";
  return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
} 
echo sum_the_time($times);
于 2012-11-24T17:10:12.767 回答
1

这在 PHP 代码中做的更少,并尽可能在 PHP 运行时中保持执行流程,用 C 编写:

<?php
$duration_c[0][0]="19:30:00";
$duration_c[0][1]="00:10:00";

$duration_c[1][0]="00:30:00";
$duration_c[1][1]="00:20:00";

$sum = 0;
foreach($duration_c as $durations) {
    $today = strtotime('today');
    $sum += array_sum(array_map(function($str) use ($today) {
        return strtotime($str)-$today;
    }, $durations));
}
echo $sum; // 73800 seconds, that's 20.5 hours
于 2012-11-24T17:13:31.790 回答
0

$times=$duration_c[$k][$s];应该是$times=$duration_c[$k];,否则您将单个时间传递给函数,而不是时间数组。

于 2012-11-24T17:09:22.000 回答