Reputation: 355
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?
Upvotes: 0
Views: 389
Reputation: 781088
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.
Upvotes: 1