Skip to content

Instantly share code, notes, and snippets.

@UziTech
Created June 17, 2016 20:41
Show Gist options
  • Save UziTech/ee60bbc31ce7a69616f11a1feded37b5 to your computer and use it in GitHub Desktop.
Save UziTech/ee60bbc31ce7a69616f11a1feded37b5 to your computer and use it in GitHub Desktop.
array_multisort_by_key
/*
* License: MIT
*/
/**
* Sort an array of associative arrays by a key. Like array_multisort but you just provide the key instead of the whole column.
* @param array[] $data The array of associative arrays to sort
* @param mixed ...$args Any number of variables. [key, SORT_ASC|SORT_DESC, Sort Flags]
* https://secure.php.net/manual/en/function.array-multisort.php
* @return array[] The sorted $data
*/
function array_multisort_by_key($data, ...$args) {
if (!is_array($data)) {
return [];
}
$params = [];
foreach ($args as $n => $arg) {
if (is_string($arg)) {
$column = [];
foreach ($data as $row) {
$column[] = $row[$arg];
}
$arg = $column;
}
$params[] = $arg;
}
$params[] = &$data;
array_multisort(...$params);
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment