dev-master
9999999-dev https://github.com/RikudouSage/php-array-sortClass for sorting arrays
WTFPL
The Requires
- php >=7
The Development Requires
by Dominik Chrástecký
array sort sorting
Class for sorting arrays
Simple class for sorting arrays, it's just a wrapper around built-in php functions., (*1)
All sorting methods are performed on a copy of array, they don't modify the original array
and return arrays. Or throw \rikudou\ArraySortException
., (*2)
Use composer: composer require rikudou/array-sort
, (*3)
For a better control the sorting methods are chained by the type., (*4)
Example:, (*5)
<?php use rikudou\ArraySort; $array = [ 1, 2, 3, 4, 5 ]; $sorter = new ArraySort($array); $sortedArray = $sorter->byValue()->maintainKeys()->sortReverse();
All methods are chained this way., (*6)
Types:
- byValue()
- maintainKeys()
- discardKeys()
- byKey()
, (*7)
This class can also be used with magic methods, so you don't have to write the whole chain., (*8)
Example:, (*9)
<?php use rikudou\ArraySort; $array = [ 1, 2, 3, 4, 5 ]; $sorter = new ArraySort($array); $sortedArray = $sorter->sortReverse();
The behavior is controlled by the precedence of classes, which by default is:, (*10)
The order can be changed by using static method setOrder()
with the help of
ArraySortPrecedenceConstants
class., (*11)
Example:, (*12)
<?php use rikudou\ArraySort; use rikudou\ArraySortPrecedenceConstants; ArraySort::setOrder([ ArraySortPrecedenceConstants::BY_KEY ]);
This sets that magic methods will by default be looked up in the by key sorting methods., (*13)
You don't have to specify all of the order, the rest will be appended automatically in default order., (*14)
So the above translates to this:, (*15)
Another example:, (*16)
<?php use rikudou\ArraySort; use rikudou\ArraySortPrecedenceConstants; ArraySort::setOrder([ ArraySortPrecedenceConstants::DISCARD_KEY ]);
This means:, (*17)
Of course you can also set the whole order:, (*18)
<?php use rikudou\ArraySort; use rikudou\ArraySortPrecedenceConstants; ArraySort::setOrder([ ArraySortPrecedenceConstants::BY_KEY, ArraySortPrecedenceConstants::BY_VALUE, ArraySortPrecedenceConstants::DISCARD_KEY, ArraySortPrecedenceConstants::MAINTAIN_KEY ]);
This translates to:, (*19)
The magic methods use reflection so it's kind of slow compared to normal chaining, but it also uses a cache, so if it finds a method in a class once, further on it uses the class without looking it up., (*20)
If you change the order, the cache is flushed and all magic method calls have to be looked up again., (*21)
All magic methods have a docblock comment so IDE should be able to hint the method names., (*22)
Class for sorting arrays
WTFPL
array sort sorting