Created
November 12, 2020 23:23
-
-
Save alpenzoo/ba28f92013fae2787522a714868aaf01 to your computer and use it in GitHub Desktop.
Sort multidimensional array in PHP.
This file contains hidden or 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 | |
function sortMultidimensionalArray($arr, $attr){ | |
// Comparison function | |
$compareTIME = function ($el1, $el2) use ($attr){ | |
$datetime1 = strtotime($el1[$attr]); | |
$datetime2 = strtotime($el2[$attr]); | |
return $datetime1 - $datetime2; | |
}; | |
$compareSTR = function ($el1, $el2) use ($attr){ | |
$s1 = $el1[$attr]; | |
$s2 = $el2[$attr]; | |
$coll = collator_create( 'en_US' ); | |
return collator_compare( $coll, $s1, $s2 ); | |
}; | |
// Sort the array | |
usort($arr, $compareSTR); | |
return $arr; | |
} | |
$array = Array ( | |
Array ( | |
"name" => "Olivia Musterman", | |
"datetime" => "2019-02-22 11:29:45", | |
), | |
Array ( | |
"name" => "Anna Musterman", | |
"datetime" => "2019-02-13 11:29:45", | |
), | |
Array ( | |
"name" => "Xenia Musterman", | |
"datetime" => "2019-02-15 11:29:45", | |
) | |
); | |
// Print the array | |
echo "<pre>"; | |
print_r(sortMultidimensionalArray($array,'name')); | |
echo "<pre>"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment