Sort an array of arrays by date in PHP

Last updated 2 years ago | 835 views 75     5

Tags:- PHP

PHP | Sort an array of arrays by date in PHP

Here a situation in which we have to sort an array of the array by date. An array of arrays is a multidimensional array in which an array holding multiple arrays as data.

the array looks like this:-

Array
    (
    [0] => Array
        (
            [id] => 2
            [name] => Jon
            [image] => jon.jpg
            [created_date] => 2019-01-30 11:29:45
        )

    [1] => Array
        (
            [id] => 3
            [name] => Adam
            [image] => adam.jpg
            [created_date] => 2019-02-5 15:59:53
        )

    [2] => Array
        (
            [id] => 4
            [name] => DK
            [image] => dk.jpg
            [created_date] => 2019-01-26 16:04:24
        )

    )

Now for sorting such array by created date. Convert created date in Linux date format

foreach ($originalArray as $key => $part) {
       $sort[$key] = strtotime($part['created_date']);
    }

In the above example, "foreach" loop is used to read the created date one by one, and "strtotime" function is used to convert the date into Linux format. $sort is an array variable that is used to store the converted Linux date.

Now use array_multisort function which is a sorting function for multidimensional array in PHP

$sorted_array = array_multisort($sort, SORT_DESC, $originalArray);

print_t($sorted_array)