简体   繁体   English

用PHP中的月份名称和年份对数组进行排序

[英]Sort array with month name and year in php

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 尝试过使用usort(), uksort() ....之类的函数usort(), uksort()但无法正常工作,请帮助我解决此问题

You can use usort and use strtotime to convert the string to time. 您可以使用usort并使用strtotime将字符串转换为时间。

$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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM