晚上好
我在这里有一个问题。我有两个数组:$ 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()提供的参数无效
答案 0 :(得分: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);
答案 1 :(得分: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
答案 2 :(得分:0)
$times=$duration_c[$k][$s];
应为$times=$duration_c[$k];
,否则您只会传递一次该函数,而不是一次数。