On another recent project I had to generate monthly reports for the clients, to allow them to select the desired report I decided on giving them two HTML select inputs, the first for year and second for month. I tied the two fields together via ajax.
To populate these select boxes I wanted to build an multi-dimensional array of dates organized by year and then by month where the first date or month available is the date the client’s account was created (a date from the database) and the last date or month to be the current.
I build the following function to build my array of years and months, it is dependent upon another function posted on this site that builds an array of individual dates. These could be combined into one ‘SUPER FUNCTION’ but there was no need as the project required both functions discretely anyway.
The function requires two input options, a starting date and an ending date. These dates must be in the ’0000-00-00′ format.
The result of:
$start = '2007-05-12'; $end = '2009-06-18'; print_r( year_month_array( $start, $end ) );
Would be:
Array
(
[2007] => Array
(
[0] => May
[1] => June
[2] => July
[3] => August
[4] => September
[5] => October
[6] => November
[7] => December
)
[2008] => Array
(
[0] => January
[1] => February
[2] => March
[3] => April
[4] => May
[5] => June
[6] => July
[7] => August
[8] => September
[9] => October
[10] => November
[11] => December
)
[2009] => Array
(
[0] => January
[1] => February
[2] => March
[3] => April
[4] => May
[5] => June
)
)
function year_month_array($from, $to)
{
$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
$dates = array_values(array_unique(get_date_range_array($from, $to, 'Y-n')));
$data = array();
foreach ( $dates as $date )
{
$date = explode('-', $date);
$data[$date[0]][] = $months[$date[1]-1];
}
return $data;
}