Last active
January 1, 2018 21:57
-
-
Save jarcos/979d57f21e00cb18ee26dcd8f0df63bf to your computer and use it in GitHub Desktop.
Sort array by date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* In this case, the value to sort is a date in string, i.e. "01/01/2018" or "2017-12-31" | |
*/ | |
/** | |
* Example of array | |
*/ | |
$array = array( | |
array( "01/01/1968", "Do Androids Dream of Electric Sheep?", "Philip K. Dick", "Philosophical novel" ), | |
array( "16/08/2011", "Ready Player One", "Ernest Cline", "Dystopian" ), | |
array( "01/01/1951", "Foundation", "Isaac Asimov", "Science Fiction" ), | |
); | |
/** | |
* Comparison function to sort the array by date | |
*/ | |
function sort_comparison( $a, $b ) { | |
return strtotime( $a[0] ) - strtotime( $b[0] ); | |
} | |
usort( $array, 'sort_comparison' ); | |
/** | |
* Result | |
* | |
* array(3) { | |
* [0]=> | |
* array(4) { | |
* [0]=> | |
* string(10) "01/01/1951" | |
* [1]=> | |
* string(10) "Foundation" | |
* [2]=> | |
* string(12) "Isaac Asimov" | |
* [3]=> | |
* string(15) "Science Fiction" | |
* } | |
* [1]=> | |
* array(4) { | |
* [0]=> | |
* string(10) "01/01/1968" | |
* [1]=> | |
* string(36) "Do Androids Dream of Electric Sheep?" | |
* [2]=> | |
* string(14) "Philip K. Dick" | |
* [3]=> | |
* string(19) "Philosophical novel" | |
* } | |
* [2]=> | |
* array(4) { | |
* [0]=> | |
* string(10) "16/08/2011" | |
* [1]=> | |
* string(16) "Ready Player One" | |
* [2]=> | |
* string(12) "Ernest Cline" | |
* [3]=> | |
* string(9) "Dystopian" | |
* } | |
* } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment