How To Use Sort Multidimensional Array By Date Element Using PHP?

03-Apr-2023

.

Admin

How To Use Sort Multidimensional Array By Date Element Using PHP?

Hi Friends,

This example is how to use sort multidimensional array by date element using 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.

So let's start following example.

Example:


<?php

// Declare a multidimensional array

// and initialize it

$array = Array (

Array (

"gfg" => "GFG_1",

"datetime" => "2021-02-22 11:29:45",

),

Array (

"gfg" => "GFG_2",

"datetime" => "2021-02-13 11:29:45",

),

Array (

"gfg" => "GFG_3",

"datetime" => "2021-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] => 2021-02-13 11:29:45

)

[1] => Array

(

[gfg] => GFG_3

[datetime] => 2021-02-15 11:29:45

)

[2] => Array

(

[gfg] => GFG_1

[datetime] => 2021-02-22 11:29:45

)

)

I hope it can help you...

#PHP