简体   繁体   中英

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. Also, the array is received through an API so I have no control over the output.

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($array);
var_dump($array);

krsort does the reverse - 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

Alternatively if your keys were unique timestamp corresponding to the date you could just use krsort.

krsort($array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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