douyong5476 2010-12-27 14:13
浏览 65
已采纳

比较多个不同的日期并获得PHP的平均值

I use a function called count_days($date1,$date2) that counts the number of days between two dates. But, my question is: the dates come from the DB, in an array like:

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

As you can see the products may have a different number of subarrays.
I want to count the days between the first and the next date (and so on!) and then get the average of days.

  • 写回答

2条回答 默认 最新

  • dry0106 2010-12-27 14:31
    关注

    The DateInterval class is great for this kind of date arithmetic. You can use DateTime::add, DateTime::subtract and DateTime::diff to work with them.

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

    This will output:

    Array (
        [imac] => Array (
                [0] => 408
                [1] => 354
            )
        [iphone] => Array (
                [0] => 244
                [1] => 398
                [2] => 356
            )
    )
    Array (
        [imac] => 381
        [iphone] => 332.66666666667
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样