phpextra / sorter
使用多字段按Unicode字符排序数组和对象
1.0.1
2016-01-12 23:29 UTC
Requires
- php: >=5.3
- ext-bcmath: *
- ext-intl: >=1.0.0
This package is not auto-updated.
Last update: 2024-09-11 13:09:42 UTC
README
##安装
使用 Composer 进行安装
composer require phpextra/sorter
您可以使用 phpunit
测试库,通过运行以下命令(假设您有可用的 phpunit
命令)
phpunit ./tests
用法
###使用默认设置排序
use PHPExtra\Sorter\Sorter; $data = array('ccc', 'aaa', 'bbb'); $sorter = new Sorter(); $data = $sorter->sort($data); print_r($data); // prints array('aaa', 'bbb', 'ccc');
###使用特定区域设置排序
UnicodeCIComparator
(不区分大小写的比较器)是本库默认使用的比较器,默认情况下,在创建时它使用当前系统区域设置(从 php.ini)。
值得注意的是,当使用此比较器时,它可能会产生对数字的 看起来很奇怪的结果。例如,
-1000
大于-100
。如果您想按实际值比较数字,请使用NumericComparator
。
use PHPExtra\Sorter\Sorter; use PHPExtra\Sorter\Strategy\SimpleSortStrategy; use PHPExtra\Sorter\Comparator\UnicodeCIComparator; $strategy = new SimpleSortStrategy(); $strategy->setComparator(new UnicodeCIComparator('pl_PL')); $sorter = new Sorter($strategy); $sorter->sort(...);
###在保持键完整的情况下排序数组
use PHPExtra\Sorter\Sorter; use PHPExtra\Sorter\Strategy\SimpleSortStrategy; use PHPExtra\Sorter\Comparator\UnicodeCIComparator; $array = array(0 => 'a', 1 => 'c', 2 => 'b'); $strategy = new SimpleSortStrategy(); $strategy->setMaintainKeyAssociation(true); $sorter = new Sorter($strategy); $sorter->sort($array); print_r($array); // prints array(0 => 'a', 2 => 'b', 1 => 'c')
###排序复杂对象
use PHPExtra\Sorter\Sorter; use PHPExtra\Sorter\Strategy\ComplexSortStrategy; $data = array( (object)array('name' => 'Ann', 'position' => '3', 'rating' => '3'), (object)array('name' => 'Ann', 'position' => '2', 'rating' => '2'), (object)array('name' => 'Ann', 'position' => '2', 'rating' => '1'), (object)array('name' => 'Betty', 'position' => '1', 'rating' => '2'), ); $strategy = new ComplexSortStrategy(); $strategy ->setSortOrder(Sorter::ASC) ->sortBy('position') // sort by position ->sortBy('name') // sort by name if position is equal ->sortBy(function($object){return $object->rating}) // sort by rating if name is equal ; $sorter = new PHPExtra\Sorter\Sorter(); $data = $sorter->setStrategy($strategy)->sort($data); print_r($data); // prints: // // Array // ( // [0] => stdClass Object // ( // [name] => Betty // [position] => 1 // [rating] => 2 // ) // // [1] => stdClass Object // ( // [name] => Ann // [position] => 2 // [rating] => 1 // ) // // [2] => stdClass Object // ( // [name] => Ann // [position] => 2 // [rating] => 2 // ) // // [3] => stdClass Object // ( // [name] => Ann // [position] => 3 // [rating] => 3 // ) // )
###自定义
您可以为更复杂的数据集创建自己的策略。提供的 ComplexSortStrategy
应该覆盖您的大部分需求,如果它不足以满足您的需求,请尝试使用您自己的比较器。您可以替换整个策略的默认比较器或仅定义特定属性的自定义比较器。
$strategy ->setSortOrder(Sorter::ASC) ->sortBy('position') ->sortBy('name', Sorter::DESC, new MyOwnPropertyComparator()) ->sortBy('rating') ; // or set your own comparator $strategy->setComparator(new MyOwnPropertyComparator());
##贡献
所有代码贡献都必须通过拉取请求进行。
将项目分支,创建功能分支,并发送给我一个拉取请求。
##作者
此库受到 https://github.com/graze/sort 的启发。
Jacek Kobus - kobus.jacek@gmail.com