用于按月份统计数据,适用于日期类型字段的区间查询。

返回值示例在函数注释里


/**
 * 获取各个月份起止时间.
 *
 * @param number $number 获取月份数,留空默认为当前月份
 * @param number $moreNumber 额外月份(大于当前月份)
 *
 * 返回值示例: array:3 [▼
  0 => array:3 [▼
    "name" => "1月"
    "start" => "2022-01-01"
    "end" => "2022-01-31"
  ]
  1 => array:3 [▼
    "name" => "2月"
    "start" => "2022-02-01"
    "end" => "2022-02-28"
  ]
  2 => array:3 [▼
    "name" => "3月"
    "start" => "2022-03-01"
    "end" => "2022-03-31"
  ]
]
 */
function getYearMonthRange($number = 0, $moreNumber = 0)
{
    $result = [];
    if (!$number) {
        //本年截止到当前月
        $number = date('n');
        for ($i = 0; $i < $number; ++$i) {
            $result[] = [
                'name' => Carbon::now()->startOfYear()->addMonth($i)->format('n') . '月',
                'start' => Carbon::now()->startOfYear()->addMonth($i)->toDateString(),
                'end' => Carbon::now()->startOfYear()->addMonth($i)->endOfMonth()->toDateString(),
            ];
        }
    } else {
        //从当前月份往前推 $number 个月, 有可能跨年
        for ($i = 0; $i < $number; ++$i) {
            $result[] = [
                'name' => Carbon::now()->addMonth(-$i)->format('n') . '月',
                'start' => Carbon::now()->addMonth(-$i)->startOfMonth()->toDateString(),
                'end' => Carbon::now()->addMonth(-$i)->endOfMonth()->toDateString(),
            ];
        }
        $result = array_reverse($result);
    }
    if ($moreNumber) {
        for ($i = 1; $i < $moreNumber + 1; ++$i) {
            $result[] = [
                'name' => Carbon::now()->addMonth($i)->format('n') . '月',
                'start' => Carbon::now()->addMonth($i)->startOfMonth()->toDateString(),
                'end' => Carbon::now()->addMonth($i)->endOfMonth()->toDateString(),
            ];
        }
    }

    return $result;
}