Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP re-order array of month names

Tags:

arrays

php

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.

like image 959
Ron Avatar asked Sep 14 '12 12:09

Ron


3 Answers

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"];
}
like image 198
Tchoupi Avatar answered Sep 25 '22 19:09

Tchoupi


$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)
like image 35
billyonecan Avatar answered Sep 25 '22 19:09

billyonecan


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;
}
like image 36
Johan Avatar answered Sep 24 '22 19:09

Johan