Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by date in descending order by date in php

Tags:

php

I have an array and I want to sort it by date. I am not able to sort it properly by date in descending order. Please help.

Array
(
[1] => Array
    (
        [1] => 11/05/2013
        [2] => Executive Planning Day
    )

[2] => Array
    (
        [1] => 13/06/2013
        [2] => Middle Leaders Planning Day
    )

[3] => Array
    (
        [1] => 12/07/2013
        [2] => New Staff Induction Day
    )

[4] => Array
    (
        [1] => 13/04/2013
        [2] => Staff Conference Day No. 1
    )

[5] => Array
    (
        [1] => 14/04/2013
        [2] => Staff Conference Day No. 2
    )

[6] => Array
    (
        [1] => 15/02/2013
        [2] => Staff Conference Day No. 3
    )

[7] => Array
    (
        [1] => 16/03/2013
        [2] => Australia Day
    )
)
like image 877
Neeraj Sharma Avatar asked May 24 '13 10:05

Neeraj Sharma


People also ask

How do I sort an array of dates in PHP?

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.

Which function sort an array in descending order in PHP?

sort() - sort arrays in ascending order. rsort() - sort arrays in descending order.

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 multi dimensional 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.


1 Answers

Use usort(Sort an array by values using a user-defined comparison function).

usort($array, function($a1, $a2) {
   $value1 = strtotime($a1['date']);
   $value2 = strtotime($a2['date']);
   return $value1 - $value2;
});
like image 113
Vivek Sadh Avatar answered Oct 30 '22 10:10

Vivek Sadh