Split an array of dates by month or year

I have an array that returns the requested series of dates that I would like to split into a month or year based on a variable.

An example of the 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" } 

To create a google chart in the Month or Year view, I need to split this array and group the Years or Months based on the preferences of the users that will be in the variable.

An example of what I need to return if in the "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 that this is a sound array, but I need to be able to do a foreach statement for each set of date arrays so that I can add all the values ​​(I need a date for the go function to get the value) and return one common value and the year that will be the same, since they are grouped, and I just blow up the year of the last array in the foreach statement.

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

 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 find a solution, keeping everything intact.

+6
source share
1 answer

Something like that?

 $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); 
+11
source

Source: https://habr.com/ru/post/908169/


All Articles