I\'ve found a few answers to sorting by value, but not key.
What I\'d like to do is a reverse sort, so with:
$nametocode[\'reallylongname\']=\'12
You can use a user defined key sort function as a callback for uksort
:
function cmp($a, $b)
{
if (strlen($a) == strlen($b))
return 0;
if (strlen($a) > strlen($b))
return 1;
return -1;
}
uksort($nametocode, "cmp");
foreach ($nametocode as $key => $value) {
echo "$key: $value\n";
}
Quick note - to reverse the sort simply switch "1" and "-1".
I have benchmarked some of sorting algorithms since performance is important for my project - here's what I've found (averaged result ran 1000x, sorted field had cca 300 elements with key size 3-50 chars):
Sometime simple foreach still wins. Using dynamic PHP features has some performance penalty, obviously.
In PHP7+ you can use uksort()
with spaceship operator and anonymous function like this:
uksort($array, function($a, $b) {
return strlen($b) <=> strlen($a);
});
A simple problem requires a simple solution ;-)
arsort($nametocode, SORT_NUMERIC);
$result = array_keys($nametocode);
Behold my powerful inline methodologies. Preserve global space for the generations to come!
uksort($data, create_function('$a,$b', 'return strlen($a) < strlen($b);'));