简体   繁体   English

如何基于2个键对PHP数组进行排序,一个键升序,另一个键降序

[英]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. 问题是,它只$order_list[$i][1]升序排序。 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. 而我还需要对$order_list[$i][2]进行排序,但是要降序。 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? 如何基于这样的2个键对数组进行排序? thanks before. 之前感谢。

As already tackled in this compendium of sorting arrays, you could just swap $a and $b to make it in descending fashion: 正如本排序数组概述中已解决的那样,您只需交换$a$b使其以降序方式即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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