如何使用PHP为数组添加时差?

shi*_*hin 2 php

我在MySQL中有以下数组结构.可能没有物品或许多物品; 这个例子只显示了三个.

Array
(
    [0] => Array
        (
            [id] => 1
            ...
            [start_time] => 09:00:00
            [finish_time] => 10:20:00
            ...
        )

    [1] => Array
        (
            [id] => 2
            ...
            [start_time] => 13:00:00
            [finish_time] => 14:20:00
            ...
        )
    [2] => Array
        (
            [id] => 23
            ...
            [start_time] => 18:05:00
            [finish_time] => 19:35:00
            ...
        )

     etc etc

)
Run Code Online (Sandbox Code Playgroud)

我想在start_time和finish_time之间添加时间差,并找出PHP的总时间.

例如,上述应产生250分钟或4小时10分钟(80分钟+ 80分钟+ 90分钟).我该怎么做呢?

Con*_*oyP 5

在PHP中:

$total_diff = 0;

foreach($items as $item)
{
    $total_diff += strtotime($item['finish_time']) - strtotime($item['start_time']);
}
Run Code Online (Sandbox Code Playgroud)

的strtotime()函数将时间值转换为秒.然后,您可以$total_diff根据需要将值转换为分钟,小时等.

如果您有权修改原始MySQL查询,则可以在单个查询中执行:

SELECT sum( UNIX_TIMESTAMP(finish_time) - UNIX_TIMESTAMP(start_time) )
FROM table
Run Code Online (Sandbox Code Playgroud)

在上面,UNIX_TIMESTAMP执行与PHP中的strtotime()相同的功能.