Comparing several different dates and getting average in PHP

I use a function called count_days($date1,$date2)that counts the number of days between two dates. But, my question is: dates are taken from the database 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, products may have a different number of subarrays.
I want to count the days between the first and next date (and so on!), And then get the average number of days.

+3
source share
2 answers

The DateInterval class is great for such 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
source

try smth like this (not verified)

$lastDate = $dbArray[0][0];
    $daysArray = array();
    foreach ( $dbArray as $value )
    {
        if ( is_array($value) )
        {
            foreach ( $value as $v )
            {
                $daysArray[] = count_days($lastDate, $v);
                $lastDate = $v;
            }
        } else {
            //not an array check if it a date and test it here
        }
    }
    $average = array_sum($daysArray)/count($daysArray);
0
source

Source: https://habr.com/ru/post/1782290/


All Articles