Skip to content

Instantly share code, notes, and snippets.

@alpenzoo
Created December 12, 2022 11:18
Show Gist options
  • Save alpenzoo/bd14f7bcb23fb651ed4f30f1ee9ec539 to your computer and use it in GitHub Desktop.
Save alpenzoo/bd14f7bcb23fb651ed4f30f1ee9ec539 to your computer and use it in GitHub Desktop.
sorts a multidimensional array by two or more attributes
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