简体   繁体   English

如何在php中按时间顺序对数组进行排序?

[英]How can I sort this array chronologically in php?

I have an array with dates, looking like this: 我有一个日期数组,看起来像这样:

  $array = array(
     "20140101000000" => "January 2014",
     "20140201000000" => "February 2014",
     "20140301000000" => "Mars 2014",
     "20130401000000" => "April 2013", // 2013 starts here
     "20130501000000" => "May 2013",
     "20130601000000" => "June 2013",
     "20130701000000" => "July 2013",
     "20130801000000" => "August 2013",
     "20130901000000" => "September 2013",
     "20131001000000" => "October 2013",
     "20131101000000" => "November 2013",
     "20131201000000" => "December 2013",
  );

And I wanted it sorted chronologically, descending and I have no idea on how to achieve this. 我想按时间顺序对它进行降序排序,而我对如何实现这一目标一无所知。 The content of this array is 12 months from current month and backwards in time. 此数组的内容是从当前月份开始的12个月,并且时间倒退。 Also, the array is received through an API so I have no control over the output. 另外,该数组是通过API接收的,因此我无法控制输出。

Basically I want it to be sorted in this format: 基本上我希望它以这种格式排序:

Mars 2014, 
February 2014, 
January 2014, 
December 2013
April 2013

键与值相关,并且易于排序,因此应该可以:

krsort($array);

As the key is a numeric value, you can simply use ksort - http://www.php.net/manual/en/function.ksort.php . 由于键是数字值,因此您可以简单地使用ksort - http: ksort

ksort($array);
var_dump($array);

krsort does the reverse - http://www.php.net/manual/en/function.krsort.php krsort正好相反- http://www.php.net/manual/en/function.krsort.php

First off you have a problem with your array, most of the items share keys. 首先,您的阵列存在问题,大多数项目共享密钥。 Therefore Once evaluated that array is going to be 因此,一旦评估,该数组将是

$array = array( 
      "20140301000000" => "Mars 2014",
      "20130301000000" => "December 2013"
);

Which isn't going to help. 这将无济于事。 Each item has to have a unique key. 每个项目必须具有唯一的密钥。

If you just look at the values of array, assuming: 如果仅查看数组的值,则假定:

$array = array(
 "January 2014",
 "February 2014",
 "Mars 2014",
 "April 2013", // 2013 starts here
 "May 2013",
 "June 2013",
 "July 2013",
 "August 2013",
 "September 2013",
 "October 2013",
 "November 2013",
 "December 2013",
);

You could then use a user defined sort routine such as 然后,您可以使用用户定义的排序例程,例如

function cmp($a, $b)
{
    if (strtotime($a) == strtotime($b)) {
        return 0;
    }
    return (strtotime($a) > strtotime($b)) ? -1 : 1;

}

usort($array, "cmp");

see here http://uk1.php.net/manual/en/function.usort.php for details on usort 有关usort的详细信息,请参见http://uk1.php.net/manual/zh/function.usort.php

Alternatively if your keys were unique timestamp corresponding to the date you could just use krsort. 另外,如果您的密钥是与日期相对应的唯一时间戳,则可以使用krsort。

krsort($array)

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

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