HomeLanguagesSort a multidimensional array by date element in PHP

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:

  • $array: This parameter specifies the array which u want to sort.
  • function_name: This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two argument are equal then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.

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
        )

)
RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS