1
votes

Having issues with syntax on part of a project I'm working on. i'm creating labels for a graph that I'm creating. For some reason it always skips the first instance of January when printing the array out from Dec, Jan, Feb. When it does the second instance it prints out just fine.

This is the section of code that I'm just not grasping the problem on. These are dates Dec 2014 - Sept 2016

/* Create labels for the graph */
    $mlist = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

    $minyear = date("y", strtotime($min_date));

    for ($i = $minimum_month; $i < $maximum_month; $i++) {
        if ($i > 12) {
            $months[] = '"' . $mlist[($i % 12)] . ' ' . ($min_year + (($i - ($i % 12)) / 12)) . '"';
        } else {
            $months[] = '"' . $mlist[($i - 1)] . ' ' . $min_year . '"';
        }
    }
    $months_labels = implode(',', $months);

Here is the output:

"Dec 2014","Feb 2015","Mar 2015","Apr 2015","May 2015","June 2015","Jul 2015","Aug 2015","Sep 2015","Oct 2015","Nov 2015","Dec 2015","Jan 2016","Feb 2016","Mar 2016","Apr 2016","May 2016","June 2016","Jul 2016","Aug 2016","Sep 2016"

This is the array months:

Array
(
    [0] => "Dec 2014"
    [1] => "Feb 2015"
    [2] => "Mar 2015"
    [3] => "Apr 2015"
    [4] => "May 2015"
    [5] => "June 2015"
    [6] => "Jul 2015"
    [7] => "Aug 2015"
    [8] => "Sep 2015"
    [9] => "Oct 2015"
    [10] => "Nov 2015"
    [11] => "Dec 2015"
    [12] => "Jan 2016"
    [13] => "Feb 2016"
    [14] => "Mar 2016"
    [15] => "Apr 2016"
    [16] => "May 2016"
    [17] => "June 2016"
    [18] => "Jul 2016"
    [19] => "Aug 2016"
    [20] => "Sep 2016"
)

Thanks for any help!

1
What are your $minimum_month and $maximum_month variables?Seva Arkhangelskiy
$minimum_month = 12 and $maximum_month = 33Philip Wiggins

1 Answers

1
votes

Iterate with 1 month ("P1M") from start date to end date with DatePeriod. Set start date and number of months to what is correct for you.

$months = 17;
$start = DateTime::createFromFormat("Y-m-d", "2014-11-01");
$end = clone $start;
$end = $end->modify(sprintf("+%d months", $months));
$interval = new DateInterval("P1M");

$iterator = new DatePeriod($start, $interval, $end);

foreach ($iterator as $date) {
    echo $date->format("M Y"), "\n";
}

Set time zone somewhere:

date_default_timezone_set("Europe/Oslo");

Result:

Nov 2014
Dec 2014
Jan 2015
Feb 2015
Mar 2015
Apr 2015
May 2015
Jun 2015
Jul 2015
Aug 2015
Sep 2015
Oct 2015
Nov 2015
Dec 2015
Jan 2016
Feb 2016
Mar 2016