dpq39825 2014-05-28 21:00
浏览 72
已采纳

获取包含多个时间值的两个数组之间的时间差

I'm using two queries to gather time values into two separate arrays. I've reversed the array orders and I want to subtract the first value in one array from the first value in the second, subtract the second value from the second value, third from third, etc. I would like to display the difference in minutes between the two arrays. Does anyone know how to do this?

Here is my code:

$sql1 = "SELECT log_time FROM log_table WHERE client_name = 'opus' AND server_protocol = '638'";
$query = $this->db->prepare($sql1);
$query->execute();
$Tim1 = $query->fetchAll();
$Tim1 = array_reverse($Tim1);

$sql2 = "SELECT log_time FROM log_table WHERE client_name = 'opus' AND server_protocol = '22'";
$query = $this->db->prepare($sql2);
$query->execute();
$Tim2 = $query->fetchAll();
$Tim2 = array_reverse($Tim2);

for ($x=0; $x<count($Tim1); $x++) {
    $result = date_diff($Tim1[0], $Tim2[0]);
}

When I print_r the array values they look like this:

print_r($Tim1);
print_r($Tim2);

Array ( [0] => stdClass Object ( [log_time] => 13:08:29 ) [1] => stdClass Object ( [log_time] => 12:15:45 ) [2] => stdClass Object ( [log_time] => 11:40:00 ) [3] => stdClass Object ( [log_time] => 09:31:46 ) ) 
Array ( [0] => stdClass Object ( [log_time] => 13:51:55 ) [1] => stdClass Object ( [log_time] => 12:29:19 ) [2] => stdClass Object ( [log_time] => 12:12:02 ) [3] => stdClass Object ( [log_time] => 09:36:48 ) ) 

print_r($result);

The difference should be around 94 minutes. When I print_r($result) I get a warning saying "date_diff() expects parameter 1 to be DateTimeInterface, object given...". Does anyone know why this is happening?

展开全部

  • 写回答

1条回答 默认 最新

  • dtz33344 2014-05-28 21:58
    关注

    You're accessing the same elements of the array each time through the loop, and you're overwriting $result rather than accumulating the differences. Try:

    $result = 0;
    for ($x=0; $x<count($Tim1); $x++) {
        $result += (strtotime($Tim1[$x]->log_time) - strtotime($Tim2[$x]->log_time));
    }
    

    $result will be the sum of the time differences in seconds. Divide by 60 to get minutes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部