0

所以我有以下数组($lifeSpanArray),我正在寻找计算两个日期之间的平均间隔。

到目前为止我所拥有的,但我认为我的想法有点错误:

<?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
    )
)
4

2 回答 2

3

尝试以下操作:

 <?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);
    }

?>
于 2014-07-15T13:39:19.877 回答
0

您的解决方案是正确的,但不要伪造从 diff 返回的对象上调用 format() 方法。

来自 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');
?>
于 2014-07-15T13:39:51.007 回答