0

I have an array and want to sort the array based on date_time. Latest date_time is on the top of the array and followed by the previous date_time. Here is the array that i need to sort.

array(3) {
  [0]=>
  array(3) {
    ["name"]=>
    string(14) "Item 1"
    ["price"]=>
    int(30)
    ["date_time"]=>
    string(19) "2021-08-03 11:42:31"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(14) "Item 2"
    ["price"]=>
    int(30)
    ["date_time"]=>
    string(19) "2021-08-15 10:44:49"
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(14) "Item 3"
    ["price"]=>
    int(30)
    ["date_time"]=>
    string(19) "2021-08-12 01:45:43"
  }

I have tried this function but not working to sort the array.

function compare_date($a, $b)
{
    $t1 = strtotime($a['date_time']);
    $t2 = strtotime($b['date_time']);
    return $t1 - $t2;
}    

usort($array1, 'compare_date');

Is the function is not correct to sort the array based on date?

Malca
  • 123
  • 2
  • 11
  • Does this answer your question? [PHP Sort a multidimensional array by element containing date](https://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date) – jspit Aug 26 '21 at 16:27

1 Answers1

0
     $array= array_column($urArray, 'date_time');

     array_multisort($array, SORT_ASC, $urArray);

learn_more bout array_multisort()

Instead of array_cloumn u can use foreach loop also