I have a array of month names currently ordered like ("April", "August", "February") etc. I would like to re order this list so that it is in a normal month order such as ("January", "February", "March")
This array is getting populated from a SHOW TABLES sql query and unfortunately the SHOW TABLES does not have a ORDER BY parameter so I think my best bet is to add them to an array and reorder the array to get what I am looking for.
Convert the months to a numerical value. Then order your array numerically using sort()
You can use this question: convert month from name to number
@Matthew's answer seems to work well:
$date = date_parse('July');;
echo $date["month"];
Working solution
$months = array("April", "August", "February");
usort($months, "compare_months");
var_dump($months);
function compare_months($a, $b) {
    $monthA = date_parse($a);
    $monthB = date_parse($b);
    return $monthA["month"] - $monthB["month"];
}
                        $input = array('May', 'December', 'March', 'July');
$output = array();
foreach($input as $month) {
    $m = date_parse($month);
    $output[$m['month']] = $month;
}
ksort($output);
var_dump($output);
outputs
array
  3 => string 'March' (length=5)
  5 => string 'May' (length=3)
  7 => string 'July' (length=4)
  12 => string 'December' (length=8)
                        This is a slightly optimized version (without date parsing) ^^
$foobar_months = array( 'april','februari', 'march', 'may', 'june', 'januari', 'august', 'october', 'july', 'november', 'december', 'september' );
usort( $foobar_months, "sortMonths" );
var_dump( $foobar_months );
function sortMonths ( $a, $b ) {
  $months = array( 'januari', 'februari', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' );
  if ( array_search( $a, $months) == array_search( $b, $months) ) return 0;
  return array_search( $a, $months) > array_search( $b, $months) ? 1 : -1;
}
                        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