计算PHP中日期数组之间的秒数 [英] Counting seconds between date array in php

查看:58
本文介绍了计算PHP中日期数组之间的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我发疯.我想做的是计算用户在某个部门停留的秒数,例如部门8.

This is driving me crazy. And what I want to do is to count the number of seconds where the user stayed in the certain department for example dept no 8.

我有这个数组:

$time = array(
  '91' => array(
       '100' => array(
            '2014/05/28 00:23:26' =>array(
               'id' =>'15',
               'time' => '2014/05/28 00:23:26',
               'dept' => '8'
              ), 
            '2014/05/28 00:25:51' =>array(
              'id' =>'15',
              'time' => '2014/05/28 00:25:51',
              'dept' => '8'
             ),
            '2014/05/28 00:27:45' =>array(
              'id' =>'15',
              'time' => '2014/05/28 00:27:45',
              'dept' => '9'
             ),
           '2014/05/28 00:28:01' =>array(
              'id' =>'15',
              'time' => '2014/05/28 00:28:01',
              'dept' => '8'
            ),
          '2014/05/28 00:30:46' =>array(
             'id' =>'15',
              'time' => '2014/05/28 00:30:46',
              'dept' => '4'
         )
      )
   )
);  

解释是:

23:26至25:51的时差为145秒.

23:26 to 25:51 has a 145 difference of seconds.

25:51到27:45相差114秒.

25:51 to 27:45 has a 114 difference of seconds.

28:01至30:46的时差为165秒.

28:01 to 30:46 has a 165 differenceof seconds.

因此,如果我们将其添加为145+ 114 +166.用户在该部门停留的总秒数为424秒.

So if we add them 145+ 114 + 166. The total seconds that the user stayed in that dept is 424 seconds.

在部门9:27:45至28:01之间有16秒的时间差.

And in dept 9: 27:45 to 28:01 has a 16 difference of seconds.

我想基于该数组实现输出:

I want to achieve the output of based on that array:

$results = array(
       '8' => '424',
       '9' => '16'
);

到目前为止,我所做的代码位于: https://eval.in/591599 我得到一些错误的结果.请一些帮助我.

The codes I've done so far is in: https://eval.in/591599 I get some wrong results. Please some help me.

推荐答案

您可以使用此答案的变体,它将适用于关联数组,就像您在这里使用的一样:

You could use a variant of this answer, which will work for associative arrays, like you have here:

foreach($time as $arr) {
    foreach($arr as $visits) {
        $visits = array_values($visits); // convert to indexed array
        foreach($visits as $i => $visit) {
            if ($i == count($visits)-1) break;
            $dept = $visit['dept'];
            $results[$dept] = (isset($results[$dept]) ? $results[$dept] : 0) +
                strtotime($visits[$i+1]['time']) - strtotime($visit['time']);
        }
    }
}

$ results 是:

Array
(
    [8] => 424
    [9] => 16
)

看到它在 eval.in

这篇关于计算PHP中日期数组之间的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆