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

时间:2016-02-10 03:37:35

标签: php arrays sorting

我有这个数组:

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

我有这个代码来对它进行排序:

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

问题是,它只是按$order_list[$i][1]升序排序。它会产生这个结果:

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

虽然我需要对$order_list[$i][2]进行排序,但要降序。所以它会产生:

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

如何根据这样的2个键对数组进行排序?谢谢。

2 个答案:

答案 0 :(得分:3)

正如已经在compendium排序数组中解决的那样,你可以交换$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

答案 1 :(得分:0)

您应该更改排序算法以检查第二列。你应该做类似以下的事情。代码中的评论。

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