本文介绍了获取两个日期之间的平均间隔PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有下面的数组($lifeSpanArray
),我想计算两个日期之间的平均间隔.
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);
}
?>
哪个输出:
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
)
)
推荐答案
尝试以下操作:
<?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);
}
?>
这篇关于获取两个日期之间的平均间隔PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!