PHP comes with very powerful time handling capabilities.

Suppose you have an array of daily steps statistics for the user:


       

$userStepReports = [
    [
        'date'= >'2017-02-06'.'total'= >652,], ['date'= >'2017-03-01'.'total'= >773,], ['date'= >'2017-03-02'.'total'= >459,]];Copy the code

If we wanted to generate a line chart of the user’s steps from February 1 to March 29, we would have to pass a large array of 57 days of data because of the limitations of some chart controls, otherwise we would generate a chart with only 3 columns of data. In this case, we have to add a large array based on the existing array, and add a total equal to 0 if there is no one.

Many students will immediately think of Carbon library, but here we use the native method, actually not complicated, code reference is as follows:


       

function getDataInTimeSpan($input, $startDate, $endDate, $dateProperty, $default)
{
    $start = new \DateTime($startDate);
    $end   = new \DateTime($endDate);

    if ($start->diff($end)->invert === 1) {
        throw new \LogicException('Start time cannot be longer than end time');
    }

    $keyedInput = [];
    foreach ($input as $value) {
        $keyedInput[$value[$dateProperty]] = $value;
    }

    $endAt   = (clone $end)->modify('+1 day')->format('Y-m-d');
    $current = clone $start;
    $output  = [];

    while (($currentDate = $current->format('Y-m-d')) !== $endAt) {
        // The new PHP 7 operator is used here
        $output[] = $keyedInput[$currentDate] ?? array_merge($default, [
                $dateProperty => $currentDate,
            ]);

        $current->modify('+1 day');
    }

    return $output;
}

$userStepReports = [
    [
        'date'= >'2017-02-06'.'total'= >652,], ['date'= >'2017-03-01'.'total'= >773,], ['date'= >'2017-03-02'.'total'= >459,]]; $reports = getDataInTimeSpan( $userStepReports,'2017-02-01'.'2017-03-29'.'date'['total'= >0]);Copy the code

read

PHP: Date/Time