1

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',.....);

4
  • 3
    What's your problem? What have you tried? Commented Jan 9, 2011 at 9:49
  • How are your dates formatted? Commented Jan 9, 2011 at 9:50
  • 1
    2010-11-01 is ambiguous. Is that YYYY-MM-DD or YYYY-DD-MM? Commented Jan 9, 2011 at 10:18
  • What is the expected result ? Commented Jan 9, 2011 at 13:57

3 Answers 3

1

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);

Output:

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

1

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;

Test It Here

2 Comments

Since when was January 2010 == January 2011? :)
@marcog: It was an example. May be someone want to get person's birthdays months wise then there is no need for year. Anyway we can also do it year wise. Answer is edited.
0

I haven't tested this at all, but assuming the array $dates is made up of timestamps, the following should work

$months = array();
foreach($dates as $date) {
$months[date('F', $date)][] = $date;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.