Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - Sort array with date as key

Hi I have an array with keys as date in this format.

$arr = array(

    "20110805" => "2",
    "20100703" => "5",
    "20110413" => "3",
    "20100805" => "4",
    "20100728" => "6",
    "20090416" => "7",
    "20080424" => "8",
    "20110819" => "1",  
);

how can I sort this array by key. Thank you.

like image 304
bharath Avatar asked Aug 20 '11 21:08

bharath


People also ask

How to sort array by date PHP?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.

What is Ksort PHP?

The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

How does Usort work in PHP?

The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.

How do I sort a 2d array in PHP?

The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.


2 Answers

A slightly more complex solution, which nonetheless works for almost any date format, is based on the uksort function.

First we define a callback function that compares two dates (comparator):

function compare_date_keys($dt1, $dt2) {
    return strtotime($dt1) - strtotime($dt2);
}

Now we can use the just defined function as the second parameter in uksort, as in the example below:

uksort($arr, "compare_date_keys");

As a result the function will treat the key as a date and sort the array in ascending order (less recent first).

Note that we can easily tweak the comparator to support different use cases. For example, sorting by date descending (most recent first) can be accomplished by simply replacing the function's return expression with the following:

return strtotime($dt2) - strtotime($dt1);
like image 143
Sal Borrelli Avatar answered Oct 07 '22 12:10

Sal Borrelli


With the dates in that format, an alphabetical comparison will work just fine. Use the PHP function ksort.

ksort($arr);
like image 30
coyotebush Avatar answered Oct 07 '22 12:10

coyotebush