且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用php在多维数组中按键排序

更新时间:2023-09-07 08:30:04

用于对具有多个键的数组进行排序的通用解决方案

根据我对这个问题的回答,这是一个非常通用的解决方案,可以在很多情况下使用.

Generic solution to sort arrays of arrays with multiple keys

Based on my answer to this question, here is a very generic solution that you can use in lots of situations.

限制::由于存在匿名函数,需要PHP> = 5.3才能工作.

Limitation: Requires PHP >= 5.3 to work, due to the presence of anonymous functions.

function make_comparer() {
    $criteriaNames = func_get_args();
    $comparer = function($first, $second) use ($criteriaNames) {
        // Do we have anything to compare?
        while(!empty($criteriaNames)) {
            // What will we compare now?
            $criterion = array_shift($criteriaNames);

            // Used to reverse the sort order by multiplying
            // 1 = ascending, -1 = descending
            $sortOrder = 1; 
            if (is_array($criterion)) {
                $sortOrder = $criterion[1] == SORT_DESC ? -1 : 1;
                $criterion = $criterion[0];
            }

            // Do the actual comparison
            if ($first[$criterion] < $second[$criterion]) {
                return -1 * $sortOrder;
            }
            else if ($first[$criterion] > $second[$criterion]) {
                return 1 * $sortOrder;
            }

        }

        // Nothing more to compare with, so $first == $second
        return 0;
    };

    return $comparer;
}

使用方法

按升序排列:

How to use it

To sort by year ascending:

uasort($array, make_comparer('Year'));

要按年份升序排序,然后按月份升序排序:

To sort by year ascending, then by month ascending:

uasort($array, make_comparer('Year', 'Month'));

要按年份降序排序,然后按月升序排序:

To sort by year descending, then by month ascending:

uasort($array, make_comparer(array('Year', SORT_DESC), 'Month'));

这最后一个是你想要的.

This last one is what you 're after.