简体   繁体   中英

Custom sorting an array in PHP

I have a simple array that I would like to sort in the following way: Critical, Major, Moderate, Minor

Array
    (
        [Major] => 9
        [Critical] => 5
        [Moderate] => 6
        [Minor] => 5
    )

I am not sure how to go about custom sorting based on the key in PHP

Something like this should work for you.

$arr = ['Major' => 9, 'Critical' => 5, 'Moderate' => 6, 'Minor' => 3];
function cmp($a, $b) {
    $order = ['Critical' => 0, 'Major' => 1, 'Moderate' => 2, 'Minor' => 3];
    return $order[$a] - $order[$b];
}

uksort($arr, "cmp");

Live example here - http://sandbox.onlinephpfunctions.com/code/ce8991112a01e020014520cafaf59d38da32c2ec

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