Created
December 12, 2022 11:18
-
-
Save alpenzoo/bd14f7bcb23fb651ed4f30f1ee9ec539 to your computer and use it in GitHub Desktop.
sorts a multidimensional array by two or more attributes
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
function sort_array_by_attributes($array, ...$attributes) | |
{ | |
// Create arrays of values to sort by | |
$sort_keys = []; | |
foreach ($attributes as $attribute) { | |
$sort_keys[] = array_column($array, $attribute); | |
} | |
// Add the array to be sorted as the last argument | |
$sort_keys[] = &$array; | |
// Sort the array by the given attributes | |
call_user_func_array('array_multisort', $sort_keys); | |
return $array; | |
} | |
$people = [ ['first_name' => 'John', 'last_name' => 'Doe'], | |
['first_name' => 'Jane', 'last_name' => 'Doe'], | |
['first_name' => 'Adam', 'last_name' => 'Smith'], | |
['first_name' => 'Eve', 'last_name' => 'Smith'], | |
]; | |
$sorted_people = sort_array_by_attributes($people, 'last_name', 'first_name'); | |
$sorted_people = sort_array_by_attributes($people, 'last_name', SORT_DESC, 'first_name', SORT_ASC); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment