Change language

Sorting multidimensional array by date element in PHP

Syntax:
boolean usort ($array, "function_name") 
Parameters:this function takes two parameters as shown in the above syntax and described below:
  • $array:This parameter specifies the array you want to sort.
  • function_name:This parameter specifies the name of a custom function that compares values ​​and sorts the array specified by the $array parameter. This function returns an integer value based on the following conditions. If the two arguments are equal, it returns 0, if the first argument is greater than the second, it returns 1, and if the first argument is less than the second, it returns -1.
Return value: this function returns a boolean value. Returns TRUE on success and FALSE on failure.We use strtotime to convert the given time string to timestamp object. Once we have the timestamps, we subtract them to make more decisions.Program :  
// 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 array print_r ( $array )  
?>
Exit:
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)) 

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method