1

I have an array like

$ar =['March 2018',
      'March 2018',
      'November 2017',
      'December 2017',
      'January 2018',
      'January 2018',
      'February 2018'
     ];

I want to sort this array with month and year. But i unable to sort this array.

Expected Output: [
     'November 2017',
      'December 2017',
       'January 2018',
      'January 2018',
      'February 2018',
      'March 2018',
      'March 2018'
];

Tried with functions like usort(), uksort() .... but its not working Please help me to solve this issue

saiibitta
  • 377
  • 2
  • 18
  • by the month and year – saiibitta Jun 07 '18 at 07:36
  • https://stackoverflow.com/questions/12424968/php-re-order-array-of-month-names - check . Accepted answer working – Jaydp Jun 07 '18 at 07:38
  • In this arrya i have month and year both there we have only month name and also what is values for variables $a and $b for function – saiibitta Jun 07 '18 at 07:43
  • 1
    Just replace `date_parse` with `strtotime` and replace `return $monthA["month"] - $monthB["month"];` with `return $monthA - $monthB;` – Jaydp Jun 07 '18 at 07:45

1 Answers1

4

You can use usort and use strtotime to convert the string to time.

$ar = ['March 2018',
  'March 2018',
  'November 2017',
  'December 2017',
  'January 2018',
  'January 2018',
  'February 2018'
];

usort( $ar , function($a, $b){
    $a = strtotime($a);
    $b = strtotime($b);
    return $a - $b;
});

echo "<pre>";
print_r( $ar );
echo "</pre>";

This will result to:

Array
(
    [0] => November 2017
    [1] => December 2017
    [2] => January 2018
    [3] => January 2018
    [4] => February 2018
    [5] => March 2018
    [6] => March 2018
)
Eddie
  • 26,593
  • 6
  • 36
  • 58
  • $ar = Array ( [0] => November 2017 [1] => December 2017 [2] => January 2018 [3] => January 2018 [4] => February 2018 [5] => March 2018 [6] => March 2018 [7] => November 2017 ); I am not able to covert from this format can please help – saiibitta Jun 07 '18 at 08:51
  • above works fine ...my original input from php coming like $ar = Array ( [0] => November 2017 [1] => December 2017 [2] => January 2018 [3] => January 2018 [4] => February 2018 [5] => March 2018 [6] => March 2018 [7] => November 2017 ); – saiibitta Jun 07 '18 at 08:58
  • Can you do a `var_export( $ar );` instead of `print_r`? – Eddie Jun 07 '18 at 09:00
  • var_export( $ar ); result like this : array ( 0 => 'December 2017', 1 => 'December 2017', 2 => 'March 2018', 4 => 'March 2018', 5 => 'February 2018'); – saiibitta Jun 07 '18 at 09:04
  • Let me know how it goes :) – Eddie Jun 07 '18 at 09:08
  • result of usort assigned to variable that is not working – saiibitta Jun 07 '18 at 09:23