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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With