需要用PHP数组中的多次值计算秒数

时间:2018-03-28 21:56:30

标签: php arrays

我在php中有一个数组

Array (
    [0] => 07:50:15-i
    [1] => 10:55:41-i
    [2] => 12:33:30-i
    [3] => 12:34:04-i
    [4] => 14:32:57-i
    [5] => 14:32:59-i
    [6] => 15:30:50-i
    [7] => 10:29:27-o
    [8] => 12:06:16-o
    [9] => 14:29:10-o
    [10] => 14:29:12-o
    [11] => 15:02:28-o
    [12] => 16:57:31-o
) 

-i值结尾的值表示intime值 -o值表示停机时间值

如何通过多次停留 - 多个时间点来计算总的银泰时间

我需要计算总的银泰时间(如果所有时间按升序排序),就好像在多次接入时间之前,应该考虑最后时间的最后时间进行计算。就像那样,如果在一个intime之前有多个停机时间,那么应该考虑最后的停机时间进行计算。

编辑1:添加了一些更多的值,以便及时和两次同时发生

1 个答案:

答案 0 :(得分:0)

我假设您要计算“内部”花费的总时间。

$times = array( // sample data
    "07:50:15-i",
    "10:55:41-i",
    "12:33:30-i",
    "12:34:04-i",
    "14:32:57-i",
    "14:32:59-i",
    "15:30:50-i",
    "10:29:27-o",
    "12:06:16-o",
    "14:29:10-o",
    "14:29:12-o",
    "15:02:28-o",
    "16:57:31-o"
);

sort($times); // get times in order

$in = false;  // state
$incur = 0;   // current intime
$intotal = 0; // total time spent inside
foreach ($times as $key => $time)
{
  // match timestamp and -i/-o
  // $m[1] will be the time
  // $m[2] will be -i/-o
  preg_match('/^([0-9:]+)(-i|-o)$/', $time, $m);

  if ($m[2] === '-i')
  {
    $in = true; // set state
    $incur = strtotime($m[1]); // memorize time
  }
  else if ($m[2] === '-o' && $in &&
    ( // look ahead for more -o or end of array
      (isset($times[$key + 1]) && substr($times[$key + 1], -2, 2) !== '-o')
      || !isset($times[$key + 1])
    )
  )
  {
    $in = false; // set state
    $intotal += strtotime($m[1]) - $incur; // add delta
  }
}

echo "Total time inside: {$intotal} seconds (= "
    . $intotal/60/60 . " hours or " . $intotal/60 . " minutes)";

产生

  

内部总时间:27665秒(= 7.6847222222222小时或461.08333333333分钟)

获取样本数据。