我使用一个名为 count_days($date1,$date2)
的函数来计算两个日期之间的天数。但是,我的问题是:日期来自数据库,数组形式如下:
Array (
[imac] => Array (
[0] => 2002-10-10
[1] => 2003-11-22
[3] => 2004-11-10
)
[iphone] => Array (
[0] => 2007-09-11
[1] => 2008-05-12
[2] => 2009-06-14
[3] => 2010-06-05
)
)
如您所见,产品可能具有不同数量的子阵列。
我想计算第一个日期和下一个日期之间的天数(依此类推!),然后计算天数的平均值。
最佳答案
DateInterval类非常适合这种日期算术。您可以使用 DateTime::add、DateTime::subtract 和 DateTime::diff 来处理它们。
<?php
$types = array(
'imac' => array ('2002-10-10', '2003-11-22', '2004-11-10'),
'iphone' => array ( '2007-09-11', '2008-05-12', '2009-06-14', '2010-06-05'),
);
$typeIntervals = array();
$typeAverage = array();
foreach ($types as $type=>$dates) {
$last = null;
$typeIntervals[$type] = array();
foreach ($dates as $date) {
$current = new DateTime($date);
if ($last) {
$interval = $current->diff($last);
$typeIntervals[$type][] = $interval->days;
}
$last = $current;
}
$typeAverage[$type] = array_sum($typeIntervals[$type]) / count($typeIntervals[$type]);
}
print_r(typeIntervals);
print_r($typeAverage);
这将输出:
Array (
[imac] => Array (
[0] => 408
[1] => 354
)
[iphone] => Array (
[0] => 244
[1] => 398
[2] => 356
)
)
Array (
[imac] => 381
[iphone] => 332.66666666667
)
关于php - 比较多个不同的日期并在 PHP 中获取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539261/