Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sort an array with uasort

I need to sort an array by values, but if values of elements are equal, I need to compare their keys and sort by them.

uasort($pages_arr, function($a, $b){
                if ($a == $b){
                   return ($key_a < $key_b) ? -1 : 1; 
                }
                return ($a < $b) ? -1 : 1;
            });

I dont understand, how can I get $key_a and $key_b values (keys of elements $a and $b). Values can be the same, keys aren't; How to resolve this problem?

like image 777
user2304996 Avatar asked Jan 20 '14 22:01

user2304996


1 Answers

Try the following, which uses the uksort function:

uksort($pages_arr, function($key_a, $key_b) use ($pages_arr) {
    $a = $pages_arr[$key_a];
    $b = $pages_arr[$key_b];
    if ($a == $b) {
       return ($key_a < $key_b) ? -1 : 1; 
    }
    return ($a < $b) ? -1 : 1;
});
like image 80
Tim Cooper Avatar answered Oct 16 '22 04:10

Tim Cooper