1

I need to sort an array of months (alphabetical months) according to their months position and not alphabetical. My script returns a list of events and builds an multi-associative arrays based on years => months e.g. 2012 => array("August","March","September"), 2013 => array("April","May"); It builds the array perfectly, but I now need to sort the months so that it would return 2012 => array("March","August","September"), 2013 => ("April","May);

Here is the script I am currently using. Note that the date field in mysql is set to DATE and not VARCHAR, and dates are entered YYYY-MM-DD

public function returnMonthsArray() {
        $sql = "SELECT `date` FROM `events` WHERE `status`=1 ORDER BY `name`";
        $results = $this->db->returnMultiAssoc($sql);
        $navArray = array();
        foreach($results as $key => $value) {
            $timestamp = strtotime($value["date"]);
            $year = date("Y",$timestamp);
            $month = date("F",$timestamp);
            if(!array_key_exists($year, $navArray)) {
                $navArray[$year] = array();
            }
            if(!in_array($month,$navArray[$year])) {
                $navArray[$year][] = $month;
            }
        }
        if(count($navArray)) {
            return $navArray;
        } else {
            return false;
        }
    }
mauzilla
  • 3,574
  • 10
  • 50
  • 86

2 Answers2

1

Have a look to this post:

PHP and Enums

By specifing an enum like behavior for the months it would be easier to sort them the way that you want.

I hopw that this is helpful to you.

Community
  • 1
  • 1
1

try this query

SELECT `date` FROM `events`
WHERE `status`=1 ORDER BY `name`"
GROUP BY MONTH(`date`)
Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36