PHP自帶了非常強大的時間處理功能。
假如有一個用戶每日步數(shù)統(tǒng)計數(shù)據的數(shù)組:
<?php
$userStepReports = [
[
'date' => '2017-02-06',
'total' => 652,
],
[
'date' => '2017-03-01',
'total' => 773,
],
[
'date' => '2017-03-02',
'total' => 459,
],
];
如果需要生成一個用戶從2月1號到3月29號的步數(shù)統(tǒng)計折線圖,因為一些圖表控件的限制,我們必須傳遞一個有57天數(shù)據的大數(shù)組,否則會生成一個只有3列數(shù)據的圖表。這種情況下,我們就得基于已有的數(shù)組去補足出一個大數(shù)組,沒有的就添加一個total等于0的數(shù)據。
很多同學會立馬想起Carbon這個庫,但這里我們用原生方法實現(xiàn),實際也并不復雜,代碼參考如下:
<?php
function getDataInTimeSpan($input, $startDate, $endDate, $dateProperty, $default)
{
$start = new \DateTime($startDate);
$end = new \DateTime($endDate);
if ($start->diff($end)->invert === 1) {
throw new \LogicException('開始時間不能大于結束時間');
}
$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) {
// 這里用了PHP 7的新操作符
$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]
);