You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现根据用户选择的起止年月生成月份年份数组

Generate Monthly Array Between Start and End Dates

Got it, let's figure out how to build that array of months between your start (November 2015) and end (March 2016) dates. The key here is to leverage date handling functions to avoid messy manual month/year calculations—especially when wrapping around years.

Approach

  1. Convert the start and end month/year pairs into DateTime objects. This makes incrementing months and checking our end condition way simpler.
  2. Loop from the start date, adding one month each time we iterate.
  3. For each date in the loop, extract the month and year, then add them as an associative array to our result set.
  4. Stop the loop once we pass the end date.

PHP Implementation

Here's a working code snippet that does exactly what you need:

// Input parameters matching your example
$monthFrom = 11;
$yearFrom = 2015;
$monthTo = 3;
$yearTo = 2016;

// Create DateTime objects for start and end dates
$startDate = DateTime::createFromFormat('Y-m-d', "$yearFrom-$monthFrom-01");
$endDate = DateTime::createFromFormat('Y-m-d', "$yearTo-$monthTo-01");

// Initialize the result array
$monthArray = [];

// Clone the start date to avoid modifying the original
$currentDate = clone $startDate;

// Loop through each month until we exceed the end date
while ($currentDate <= $endDate) {
    $monthArray[] = [
        'month' => $currentDate->format('m'), // 2-digit month (e.g., '11', '01')
        'year' => $currentDate->format('Y')   // 4-digit year
    ];
    // Add one month to the current date
    $currentDate->modify('+1 month');
}

// Output the final array
print_r($monthArray);

What This Produces

When you run this code, it will output exactly the array you provided (with a minor tweak of 2-digit months—see note below):

Array
(
    [0] => Array
        (
            [month] => 11
            [year] => 2015
        )

    [1] => Array
        (
            [month] => 12
            [year] => 2015
        )

    [2] => Array
        (
            [month] => 01
            [year] => 2016
        )

    [3] => Array
        (
            [month] => 02
            [year] => 2016
        )

    [4] => Array
        (
            [month] => 03
            [year] => 2016
        )

)
  • If you prefer single-digit months (like '1' instead of '01'), just change the format string from 'm' to 'n' in the format() calls.

This method is robust—it handles all edge cases, whether you're spanning a few months in the same year or multiple consecutive years. No manual counting or error-prone conditional checks required!

内容的提问来源于stack exchange,提问作者Yandra Adie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:46:25