3

I have an array like below. I want to sort this array in descending order using date. But my code is not working.

$tbData = Array
(
    [0] => Array
        (
            [0] => Baby Boo
            [1] => 31921
            [2] => 07 Oct, 2016 07:27 pm
        )

   [1] => Array
        (
            [0] => Moonshine
            [1] => 32110
            [2] => 07 Oct, 2016 09:12 pm
        )


    [2] => Array
        (
            [0] => Hulk
            [1] => 31374
            [2] => 13 Sep, 2016 03:00 pm
        )

    [3] => Array
        (
            [0] => Sweet SHAI
            [1] => 667
            [2] => 05 Oct, 2016 09:36 am
        )

    [4] => Array
        (
            [0] => Hulk
            [1] => 31374
            [2] => 13 Sep, 2016 03:01 pm
        )

    [5] => Array
        (
            [0] => Maple
            [1] => 2270
            [2] => 08 Oct, 2016 07:31 am
        )

    [6] => Array
        (
            [0] => Josie
            [1] => 
            [2] => 08 Oct, 2016 04:40 pm
        )
)

I am trying to solve this question using this Stack Overflow question. But it's not working for me.

My code is like below:

$name = 2;
usort($tbData, function ($a, $b) use (&$name) {
     return strtotime($a[$name]) - strtotime($b[$name]);
});

My date column filed is something different. That's why may be my code is not working. Is there any other solution?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Faisal
  • 4,591
  • 3
  • 40
  • 49
  • Related: [Convert one date format into another in PHP](https://stackoverflow.com/q/2167916/2943403) and [Sort array of objects by date field](https://stackoverflow.com/a/67108550/2943403) – mickmackusa Aug 14 '22 at 21:31

1 Answers1

2

As said in the comments, the core issue here is that strtotime doesn't understand your date time format. You could have figured that out by looking at the return value, which is FALSE if conversion fails.

So, the solution is to use another function to do the conversion, eg date_create_from_format and extract the epoch second value from that DateTime using date_timestamp_get to compare those, like this:

usort($tbData, function ($a, $b) {
    $sa = date_create_from_format('d M, Y H:i a',$a[2]);
    $sb = date_create_from_format('d M, Y H:i a',$b[2]);
    return date_timestamp_get($sa) - date_timestamp_get($sb);
});
fvu
  • 32,488
  • 6
  • 61
  • 79
  • Thanks its working. but its ascending order. I think your return function like this for descending order. return date_timestamp_get($sb) - date_timestamp_get($sa); – Faisal Oct 10 '16 at 05:23