Open In App

Sort a multidimensional array by date element in PHP

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.

Syntax:



boolean usort( $array, "function_name")

Parameters: This function accepts two parameters as shown in the above syntax and are described below:

Return Value: This function returns Boolean type value. It returns TRUE in case of success and FALSE in case of failure.



We use strtotime to convert given time string to a timestamp object. Once we have timestamps, we subtract them to decide greater.

Program:




<?php
  
// Declare a multidimensional array
// and initialize it
$array = Array (
    Array (
        "gfg" => "GFG_1",
        "datetime" => "2019-02-22 11:29:45",
        ),
    Array (
        "gfg" => "GFG_2",
        "datetime" => "2019-02-13 11:29:45",
    ),
    Array (
        "gfg" => "GFG_3",
        "datetime" => "2019-02-15 11:29:45",
    )
);
  
// Comparison function
function date_compare($element1, $element2) {
    $datetime1 = strtotime($element1['datetime']);
    $datetime2 = strtotime($element2['datetime']);
    return $datetime1 - $datetime2;
  
// Sort the array 
usort($array, 'date_compare');
  
// Print the array
print_r($array)
  
?>

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

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

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

)

Article Tags :