Sort Multidimensional Array By Date Element Using PHP

Dec 24, 2021 . Admin



Hello Dev,

Now let's see example of how to use sort multidimensional array by date element example. We will check how to use sort multidimensional array by date element. This is a short guide on use sort multidimensional array by date element in php. Let's get started with how to use sort multidimensional array by date element in php.

Here i will give you many example how to use sort multidimensional array by date element using php.

Example : 1
<?php

    // Declare multidimensional array
    //initialization
    $array = Array (
        Array (
            "test" => "TEST_1",
            "datetime" => "2019-02-22 11:29:45",
        ),
        Array (
            "test" => "TEST_2",
            "datetime" => "2019-02-13 11:29:45",
        ),
        Array (
            "test" => "TEST_3",
            "datetime" => "2019-02-15 11:29:45",
        )
    );

    // Comparison function
    function dtCompare($ele1, $ele2) {
        $datetime1 = strtotime($ele1['datetime']);
        $datetime2 = strtotime($ele2['datetime']);
        return $datetime1 - $datetime2;
    }

    // Sort the array
    usort($array, 'dtCompare');

    // Print the array
    print_r($array)

?>

Output:
Array
(
    [0] => Array
        (
            [test] => TEST_2
            [datetime] => 2019-02-13 11:29:45
        )

    [1] => Array
        (
            [test] => TEST_3
            [datetime] => 2019-02-15 11:29:45
        )

    [2] => Array
        (
            [test] => TEST_1
            [datetime] => 2019-02-22 11:29:45
        )

)

It will help you...

#PHP