问题
So I have the following array ($lifeSpanArray
) and I'm looking to calculate the average interval between the two dates.
What I have so far, but I think I'm thinking slightly wrong with it:
<?php
foreach ($lifeSpanArray as $key) {
$newTimeAdd = new DateTime($key["timeAdded"]);
$newTimeRead = new DateTime($key["timeRead"]);
$interval = $newTimeAdd->diff($newTimeRead);
var_dump($interval);
}
?>
Which outputs:
Array
(
[0] => Array
(
[timeAdded] => 07/15/2014
[timeRead] => 07/15/2014
)
[1] => Array
(
[timeAdded] => 07/14/2014
[timeRead] => 07/14/2014
)
[2] => Array
(
[timeAdded] => 07/13/2014
[timeRead] => 07/15/2014
)
[3] => Array
(
[timeAdded] => 07/13/2014
[timeRead] => 07/13/2014
)
[4] => Array
(
[timeAdded] => 07/12/2014
[timeRead] => 07/12/2014
)
[5] => Array
(
[timeAdded] => 07/12/2014
[timeRead] => 07/12/2014
)
[6] => Array
(
[timeAdded] => 07/12/2014
[timeRead] => 07/12/2014
)
[7] => Array
(
[timeAdded] => 07/12/2014
[timeRead] => 07/12/2014
)
[8] => Array
(
[timeAdded] => 07/12/2014
[timeRead] => 07/12/2014
)
[9] => Array
(
[timeAdded] => 07/11/2014
[timeRead] => 07/11/2014
)
[10] => Array
(
[timeAdded] => 07/11/2014
[timeRead] => 07/11/2014
)
[11] => Array
(
[timeAdded] => 07/10/2014
[timeRead] => 07/11/2014
)
[12] => Array
(
[timeAdded] => 07/10/2014
[timeRead] => 07/10/2014
)
)
回答1:
Try the following:
<?php
$intervals = array();
foreach ($lifeSpanArray as $key) {
$newTimeAdd = new DateTime($key["timeAdded"]);
$newTimeRead = new DateTime($key["timeRead"]);
$interval = $newTimeAdd->diff($newTimeRead);
$intervals[] = $interval->days;//get days
}
if(!empty($intervals))
{
$average = average($intervals);
}
function average($arr)
{
return array_sum($arr)/count($arr);
}
?>
回答2:
Your solution is correct but do not forger to call the format() method on the returned object from diff.
Example from PHP.net :
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
来源:https://stackoverflow.com/questions/24759729/get-average-interval-between-two-dates-php