I have an array containing dates i want to make subsets of this array month wise?
dates in array are in format i.e. $dates = array('2010-11-01',.....);
3 Answers
There is no need to use the date class. Instead, we can just use substr() to get the YYYY-MM and index by that.
$dates = array('2010-11-11', '2010-01-14', '2010-01-17', '2011-01-03');
$months = array();
foreach($dates as $date) {
$month = substr($date, 0, 6);
$months[$month][] = $date;
}
print_r($months);
Array
(
[2010-1] => Array
(
[0] => 2010-11-11
)
[2010-0] => Array
(
[0] => 2010-01-14
[1] => 2010-01-17
)
[2011-0] => Array
(
[0] => 2011-01-03
)
)
Comments
Note: It will not only support your date format but also many other date formats. You can also use months in numeric or alphabetical representation.
You can loop it something like this:
$arr = array( '2009-1-1', '2009-2-1','2009-3-1','2009-3-1' );
$output = array();
foreach( $arr as $date ){
$output[date('m', strtotime($date))][] = $date;
}
print_r($output);
Test It Here
You can use month name also:
$output[date('M', strtotime($date))][] = $date;
Test It Here
For year wise months you can do it something like this:
$output[date('y', strtotime($date))][date('m', strtotime($date))][] = $date;
2010-11-01is ambiguous. Is that YYYY-MM-DD or YYYY-DD-MM?