Sort an array of array by date in PHP


Sort an array of array by date in PHP

Here a situation in which we have to sort an array of array by date. Array of array is a multi dimensional array in which an array holding multiple array as data.

the array is look like this:-

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

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

    [2] => Array
            [id] => 4
            [name] => DK
            [image] => dk.jpg
            [created] => 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 use to read created date one by one and strtotime function is use to convert date in linux format. $sort is an array variable which is use to store the converted date.

Now use array_multisort function which is a sorting function for multi dimensional array in php

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




Today spacial posts