jmf / sort
Sort arrays by key, property, etc.
1.0.0
2024-06-01 15:40 UTC
Requires
- php: >=8.3
- symfony/property-access: ^6.0|^7.0
- webmozart/assert: ^1.0
Requires (Dev)
- phing/phing: ^2.17
- phpmd/phpmd: ^2.13
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^11.1
- rector/rector: ^1.0
- squizlabs/php_codesniffer: ^3.8
README
Installation & Requirements
Install with Composer:
composer require jmf/sort
Usage
Associative sorter
Sorts provided array, preserving key-value association.
<?php use Jmf\Sort\AssociativeSorter; $sorter = new AssociativeSorter(); $unsorted = [ 'foo' => 'def', 'bar' => 'abc', 'baz' => 'ghi', ]; $sorted = $sorter->sort($unsorted);
By key sorter
Sorts provided array by key.
<?php use Jmf\Sort\ByKeySorter; $sorter = new ByKeySorter(); $unsorted = [ 'def' => 'foo', 'abc' => 'bar', 'ghi' => 'baz', ]; $sorted = $sorter->sort($unsorted);
By value sorter
Sorts provided array by value, losing key-value association.
<?php use Jmf\Sort\ByValueSorter; $sorter = new ByValueSorter(); $unsorted = [ 'def', 'abc', 'ghi', ]; $sorted = $sorter->sort($unsorted);
By property sorter
Sorts provided array of arrays, or array of objects, based on one or more properties, and preserving key-value association.
Property path syntax is from Symfony PropertyAccess component.
Sorting arrays
<?php use Jmf\Sort\ByPropertySorter; $sorter = ByPropertySorter::createDefault(); $unsorted = [ ['foo' => 'def', 'bar' => 123], ['foo' => 'abc', 'bar' => 123], ['foo' => 'abc', 'bar' => 23], ['foo' => 'ghi', 'bar' => 345], ]; $sorted = $sorter->sort( $unsorted, [ PropertyPass::asc( '[foo]', ), PropertyPass::desc( '[bar]', SORT_NUMERIC, ), ] );
Sorting objects
<?php use Jmf\Sort\ByPropertySorter; $sorter = ByPropertySorter::createDefault(); $articles = getArticles(); // Objects from a repository. $sorted = $sorter->sort( $articles, [ PropertyPass::desc( 'publicationDate', ), PropertyPass::asc( 'author.name', ), PropertyPass::asc( 'title', ), ] );