Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split up Array of Dates based on Month or Year

I have an Array that returns a requested series of dates that I would like to break apart by either Month or Year based on a variable.

Example of current array:

array(4) {

[0]=> string(10) "2012-02-01"

[1]=> string(10) "2012-02-02"

[2]=> string(10) "2011-02-03"

[3]=> string(10) "2011-03-04"

[4]=> string(10) "2011-04-05"

}

In order to generate a google chart in "Month" or "Year" view I need to break this array apart and group together the "Years" or "Months" based on a users preference which will be in a variable.

Example of what I need returned if in "Year View"

array(2) {

 [0]=> Array(2) {

       [0]=> string(10) "2012-02-01"

       [1]=> string(10) "2012-02-02"

}

 [1]=> Array(3) {

       [0]=> string(10) "2011-02-03"

       [1]=> string(10) "2011-03-14"

       [2]=> string(10) "2011-04-18"

} 

}

Not 100% sure if that is a sound array, but I need to be able to do a "foreach" statement for each array set of dates so I can add up all the values (all I need is date for function to go get the value) and return one total value and the year which will all be the same since they are grouped and I'll just explode the year of the last array in the foreach statement.

Here is the same expected result but in "Month" view mode

array(3) {

 [0]=> Array(3) {

       [0]=> string(10) "2012-02-01"

       [1]=> string(10) "2012-02-02"

       [2]=> string(10) "2011-02-03"

}

 [1]=> Array(1) {



       [1]=> string(10) "2011-03-14"

} 

 [2]=> Array(1) {

       [1]=> string(10) "2011-04-18"

} 

}

Any help would be greatly appreciated! I just can't seem to find a solution while keeping everything intact.

like image 319
Sumohax0r Avatar asked Feb 10 '12 18:02

Sumohax0r


1 Answers

Something like this?

$years = Array();
$months = Array();
foreach($dates as $d) {
    list($y,$m) = explode("-",$d);
    $years[$y][] = $d;
    $months[$y."-".$m][] = $d;
}
$years = array_values($years);
$months = array_values($months);

var_dump($years,$months);
like image 147
Niet the Dark Absol Avatar answered Sep 28 '22 18:09

Niet the Dark Absol