phparrayssortingdatetimemultidimensional-array

Sort a 2d array by a date column formatted as d M, Y H:i a


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 field is something different. That's why may be my code is not working. Is there any other solution?


Solution

  • 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);
    });