sgh / comparable-arrays

提供数组通用的比较器。

v1.0.2 2015-04-06 15:41 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:37:27 UTC


README

Author Latest Version Software License Build Status

此包提供实现了SPL ArrayAccess接口的数组和对象的比较器。它们可以与Comparable包中的排序和比较工具一起使用。

要求

此包需要PHP 5.4或更高版本,以及版本1.0或更高版本的Comparable包。

安装

通过Composer

$ composer require sgh/comparable-arrays

用法

以下是比较器:

  • KeyComparator:使用具有特定键的数组项进行比较
  • MultiKeyComparator:相同,但可以选择按多个键排序(即,在相等的情况下回退)

您可以使用所有 \SGH\Comparable\SortFunctions\SGH\Comparable\SetFunctions 中的方法与比较器一起使用。

KeyComparator 示例

use SGH\Comparable\SortFunctions;
use SGH\Comparable\Comparator\StringComparator;
use SGH\Comparable\Arrays\Comparator\KeyComparator;

$arrayOfBooks = array(
    [ 'title' => 'Design Patterns', 'author' => 'Gang of Four', 'year' => 1995 ],
    [ 'title' => 'Clean Code', 'author' => 'Uncle Bob', 'year' => 2008 ],
    [ 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999 ],
    [ 'title' => 'Patterns of Enterprise Application Architecture', 'autor' => 'Martin Fowler', 'year' => 2002 ],
);

// Sort the array of books by year:
SortFunctions::sort($arrayOfBooks, new KeyComparator('year'));

// Sort the array of books by title:
SortFunctions::sort($arrayOfBooks, new KeyComparator('title', new StringComparator));

默认用于比较数组项的比较器是 NumericComparator,它比较任何标量值并将它们视为数字。要按标题排序,我们需要显式指定比较器。

如果您愿意,您也可以使用工厂方法 ::callback() 来检索比较回调,该回调可以用于任何期望用户定义比较回调的函数

usort($arrayOfBooks, KeyComparator::callback('title', new StringComparator));

MultiKeyComparator 示例

use SGH\Comparable\SortFunctions;
use SGH\Comparable\Comparator\ReverseComparator;
use SGH\Comparable\Comparator\StringComparator;
use SGH\Comparable\Arrays\Comparator\MultiKeyComparator;

$arrayOfBooks = array(
    [ 'title' => 'Design Patterns', 'author' => 'Gang of Four', 'year' => 1995 ],
    [ 'title' => 'Clean Code', 'author' => 'Uncle Bob', 'year' => 2008 ],
    [ 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999 ],
    [ 'title' => 'Patterns of Enterprise Application Architecture', 'autor' => 'Martin Fowler', 'year' => 2002 ],
);

// Sort the array of books by author, then by year, descending:
SortFunctions::sort($arrayOfBooks, new MultiKeyComparator([
	'author' => new StringComparator,
	'year'   => new ReverseComparator(new NumericComparator)
]));

配置

KeyComparatorMultiKeyComparator 都接受实现 ArrayAccess 的数组和对象作为参数。此默认行为可以更改,以便它们只接受数组

$comparator->setAcceptArrayAccessObject(false);

默认情况下,数组键必须存在才能比较其值。这两个比较器都有非严格模式,其中缺失的项目被视为小于所有其他内容。两个缺失的项目被视为相等。

$comparator->setStrict(false);

测试

$ phpunit

贡献

有关详细信息,请参阅 CONTRIBUTING

安全性

如果您发现任何与安全性相关的问题,请通过电子邮件 fschmengler@sgh-it.eu 而不是使用问题跟踪器。

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件