PHP reorders array of month names

I have an array of month names that are currently ordered as ("April", "August", "February"), etc. I would like to order this list so that it is in the usual monthly order, for example ("January", "February", "March")

This array is populated from a SHOW TABLES sql query, and unfortunately, SHOW TABLES does not have an ORDER BY parameter, so I think it's best to add them to the array and reorder the array to get what I'm looking for.

+6
source share
5 answers

Convert months to a numeric value. Then arrange the array with 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"]; } 
+14
source
 $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); 

<strong> exits

 array 3 => string 'March' (length=5) 5 => string 'May' (length=3) 7 => string 'July' (length=4) 12 => string 'December' (length=8) 
+1
source

This is a slightly optimized version (no 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; } 
+1
source

It is impossible to sort the array as a separate array, since the system does not know that January comes first, then February, etc. You can define a hash first, for example

 a = {'January':0,'February':1,...'December':11} 

Then you can sort the array this way

 array_to_be_sorted = sorted(array_to_be_sorted, key = lambda(x): a[x]) 
0
source

You can follow the next step.

  • Get the output of SHOW TABLES, which will be displayed in the list of months ("April", "August", "February").
  • pass this to switch case, as shown below. $ output_show_tables = ("April", "August", "February") $ order_month_list = array (); foreach ($ output_show_tables as $ month) {

Switch ($ per month) case 'january': $ order_month_list [1] = January; break; $ order_month_list [2] = February; break; .. ... $ order_month_list [12] = December; break;

}

  • Now you get a list of orders for a month.
0
source

Source: https://habr.com/ru/post/925416/


All Articles