Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.