简体   繁体   中英

How to Sort PHP Array Based On 2 Keys, One is Ascending And The Other is Descending

I have this array :

$order_list = array ( array ("tangible", 1, 8, 1, 19000),
                      array ("tangible", 6, 2, 10, NULL),
                      array ("tangible", 1, 17, 1, 28000));

and I have this code to sort it :

usort($order_list, function ($a, $b) {
    if ($a[1] == $b[1]) return 0;
    return (int) $a[1] < (int) $b[1] ? -1 : 1;
});

the problem is, it only sort $order_list[$i][1] ascending. it will produce this result :

array ("tangible", 1, 8, 1, 19000)
array ("tangible", 1, 17, 1, 28000)

while I need $order_list[$i][2] also to be sorted, but descending. so it will produce :

array ("tangible", 1, 17, 1, 28000)
array ("tangible", 1, 8, 1, 19000)
array ("tangible", 6, 2, 10, NULL)

how to sort an array based on 2 keys like this? thanks before.

As already tackled in this compendium of sorting arrays, you could just swap $a and $b to make it in descending fashion:

usort($order_list, function ($a, $b) {
    if( ($c = $a[1] - $b[1]) !== 0) {
        return $c;
    } else {
        return $b[2] - $a[2]; // descending
    }
});

Sample Output

you should change the sort algorithm to check the second column also. you should do something like the following. comments in code.

usort($order_list, function ($a, $b) {
    // if both columns are same return 0
    if ((int) $a[1] == (int) $b[1] && (int) $a[2] == (int) $b[2]) return 0;
    // if first column is equal sort on the second column
    if ((int) $a[1] == (int) $b[1]){
        return (int) $a[2] > (int) $b[2] ? -1 : 1;
    }
    // else sort on the first column
    return (int) $a[1] < (int) $b[1] ? -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