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
- Convert the start and end month/year pairs into
DateTimeobjects. This makes incrementing months and checking our end condition way simpler. - Loop from the start date, adding one month each time we iterate.
- For each date in the loop, extract the month and year, then add them as an associative array to our result set.
- 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 theformat()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
相关产品推荐
相关产品推荐

