For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.
<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
if ($valrev) { arsort($array); } else { asort($array); }
$vals = array_count_values($array);
$i = 0;
foreach ($vals AS $val=>$num) {
$first = array_splice($array,0,$i);
$tmp = array_splice($array,0,$num);
if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
$array = array_merge($first,$tmp,$array);
unset($tmp);
$i = $num;
}
}
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);
asort($tmp);
print_r($tmp);
aksort($tmp);
print_r($tmp);
aksort($tmp,true);
print_r($tmp);
aksort($tmp,true,true);
print_r($tmp);
Array
(
[pe] => 1
[ca] => 1
[ce] => 1
[cb] => 2
[pa] => 2
)
Array
(
[ca] => 1
[ce] => 1
[pe] => 1
[cb] => 2
[pa] => 2
)
Array
(
[cb] => 2
[pa] => 2
[ca] => 1
[ce] => 1
[pe] => 1
)
Array
(
[pa] => 2
[cb] => 2
[pe] => 1
[ce] => 1
[ca] => 1
)