Skip to content

Instantly share code, notes, and snippets.

@jarcos
Last active January 1, 2018 21:57
Show Gist options
  • Save jarcos/979d57f21e00cb18ee26dcd8f0df63bf to your computer and use it in GitHub Desktop.
Save jarcos/979d57f21e00cb18ee26dcd8f0df63bf to your computer and use it in GitHub Desktop.
Sort array by date
<?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