我正在使用两个查询将时间值收集到两个单独的数组中。我已经颠倒了数组顺序,我想从第二个值中的第一个值中减去一个数组中的第一个值,从第二个值中减去第二个值,从第三个值减去第三个值,等等。我想在几分钟内显示差异两个数组之间。有谁知道怎么做?
这是我的代码:
$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]);
}
当我print_r数组值时,它们看起来像这样:
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);
差异应该在 94 分钟左右。当我print_r($ result)时,我收到一条警告,说“date_diff()期望参数1为DateTimeInterface,对象给定......”。有谁知道为什么会这样?
答案 0 :(得分:1)
您每次循环访问数组的相同元素,并且您将覆盖$result
而不是累积差异。尝试:
$result = 0;
for ($x=0; $x<count($Tim1); $x++) {
$result += (strtotime($Tim1[$x]->log_time) - strtotime($Tim2[$x]->log_time));
}
$result
将是以秒为单位的时差之和。除以60得到分钟。