使用Nspl中的sorted function对数组进行排序非常方便:
基本分类
// Sort array
$sorted = sorted([3, 1, 2]);
// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);
按函数结果排序
// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');
// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; });
// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));
// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0
多维数组排序
// Sort multidimensional array (sort list of users by their names)
$users = [
array('name' => 'Robert', 'age' => 20),
array('name' => 'Alex', 'age' => 30),
array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));
// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key
对象排序数组
// Lets assume we have class User(name, age) with properties name and age
// and public methods getName() and getAge()
$users = [
new User('Robert', 20),
new User('Alex', 30),
new User('Jack', 25),
];
// Sort list of objects by property value (sort list of users by their name)
$sortedByName = sorted($users, propertyGetter('name'));
$sortedByNameDesc = sorted($users, true, propertyGetter('name'));
// propertyGetter('name') returns a function which takes an object
// and returns the value of its 'name' property
// Sort list of objects by method result (sort list of users by their age)
$sortedByAge = sorted($users, methodCaller('getAge'));
$sortedByAgeDesc = sorted($users, true, methodCaller('getAge'));
// methodCaller('getAge') returns a function which takes an object
// and returns the result of its getAge() method
用比较函数排序
// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');
// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
return chr($v1[0]) - chr($v2[0]);
});
你可以在这里看到所有这些例子。