简体   繁体   中英

uksort by multiple array elements

I have an array that looks like this (sample):

Array
(
    [1600] => Array
        (
            [country] => Canada
            [memTypeID] => 10
        )

    [1601] => Array
        (
            [country] => United States
            [memTypeID] => 7
        )

    [1602] => Array
        (
            [country] => Canada
            [memTypeID] => 9
        )
)

I need to sort by country and then memTypeID, while preserving the array key (in PHP). I believe I need to use uksort, as usort rewrites the array keys. I know how to create a simple comparison function on one array element, but am at a loss as to how I can handle two.

The resulting array should be:

Array
(
    [1602] => Array
        (
            [country] => Canada
            [memTypeID] => 9
        )
    [1600] => Array
        (
            [country] => Canada
            [memTypeID] => 10
        )

    [1601] => Array
        (
            [country] => United States
            [memTypeID] => 7
        )


)
function cmp($a, $b) {
     if(strcmp($a['country'],$b['country']) != 0) {
         return $a['country'] > $b['country'] ? 1 : -1;
     }
   return $a['memTypeID'] > $b['memTypeID'] ? 1 : -1;
}

uasort($a, "cmp");

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