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.
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.
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.
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.
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.
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);
With the dates in that format, an alphabetical comparison will work just fine. Use the PHP function ksort.
ksort($arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With