简体   繁体   中英

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?

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM