11 September 2013
11 September 2013,
 3

Working on WP e-Customers right now and adding some charts. A bar graph displaying registrations from the last twelve month is the first. I quickly came up with a way to establish 12 months backwards.

                    <?php
                    $months_array = array('january','february','march','april','may','june','july','august','september','october','november','december');
                    $months_array_reversed = array_reverse($months_array,true);

                    $reached_this_month = false;# once true it indicates the foreach has arrived at the current month
                    $months_past = array();# our final array of months

                    // loop to the current month then start adding all remaining months to our $months_past array
                    foreach($months_array_reversed as $key => $month){

                        // only add months to our final array once we have already reached the current month
                        if($reached_this_month){
                            $months_past[]['month'] = $key;
                            $months_past[]['monthname'] = $month;
                            $months_past[]['year'] = date('Y');
                        }

                        // when we reach current month
                        if($key == date('n')){
                            $reached_this_month = true;
                        }
                    }

                    // add remaining months starting from December
                    if(date('n') != 12){
                        foreach($months_array_reversed as $key => $month){
                            $months_past[]['month'] = $key;
                            $months_past[]['monthname'] = $month;
                            $months_past[]['year'] = date('Y') - 1;

                            // once we have twelve months we are done
                            if(count($months_past) == 12){break;}
                        }
                    }
                    ?>