如何在php中对数组中的时间值求和 [英] how to sum time value in array in php
问题描述
我正在根据客户端ID从我的数据库中获取数据.客户ID的工作时间不同,例如:
i am fetching a data from my database according to client id. client id work time is different like:
00:15:0000:20:00等
00:15:00 00:20:00 etc.
这不是数组我将其作为动态数组
this is not an array i make this as dynamic array
$time[] = $alltime;
显示此结果:
Array
(
[0] => 00:20:00
[1] => 00:15:00
[2] => 00:20:00
[3] => 00:20:00
[4] => 00:55:00
[5] => 00:05:00
)
我想一直累加.我尝试了很多次,但是没有按照时间显示输出.请帮助
i want to sum all time. i tried many times and many way but output not showing according to time. please help
推荐答案
这是使用 strtotime
将时间转换为秒.请注意,由于 strtotime
会产生一个相对于Unix纪元的时间戳,因此您需要从每个值中减去一天的开始时间( strtotime('00:00')
)到获取时间中的秒数:
Here's one way to get the sum, using strtotime
to convert the times to seconds. Note that since strtotime
produces a timestamp relative to the Unix Epoch, you need to subtract the start of the day (strtotime('00:00')
) from each value to get the number of seconds in the time:
$time = array
(
'00:20:00',
'00:15:00',
'00:20:00',
'00:20:00',
'00:55:00',
'00:05:00'
);
$time_in_secs = array_map(function ($v) { return strtotime($v) - strtotime('00:00'); }, $time);
$total_time = array_sum($time_in_secs);
$hours = floor($total_time / 3600);
$minutes = floor(($total_time % 3600) / 60);
$seconds = $total_time % 60;
echo "Total time is "
. str_pad($hours, 2, '0', STR_PAD_LEFT)
. ":" . str_pad($minutes, 2, '0', STR_PAD_LEFT)
. ":" . str_pad($seconds, 2, '0', STR_PAD_LEFT) . "\n";
输出:
Total time is 02:15:00
您还可以通过使用 array_reduce
来计算 $ total_time
,而不是 array_map
和 array_sum
:
You could also simplify the code by using array_reduce
to compute $total_time
instead of array_map
and array_sum
:
$total_time = array_reduce($time, function ($c, $v) { return $c + strtotime($v) - strtotime('00:00'); }, 0);
这篇关于如何在php中对数组中的时间值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!