arifulhb/php-algorithms

PHP中的多维数组与对象排序

v0.1.1 2021-06-08 15:40 UTC

This package is not auto-updated.

Last update: 2024-09-26 05:55:26 UTC


README

按字符串、整数或两者排序多维 arrayobject

安装

在您的php应用程序中安装此包。

composer require arifulhb/php-algorithms

按数组排序

例如,如果您有一个数组,并且您想按名称或按价格排序或两者都排序,您可以使用此包进行排序。

 $items = [
    [
        'name' => 'computer',
        'price' => 4,
    ],
    [
        'name' => 'tv',
        'price' => 9,
    ],
    [
        'name' => 'apple',
        'price' => 1,
    ],
    [
        'name' => 'airpod',
        'price' => 1,
    ],
    [
        'name' => 'airtag',
        'price' => 3,
    ],
    [
        'name' => 'shampoo',
        'price' => 5,
    ]
];

如何

// create a configuration object specifying integer and string field accordingly.
$config = new SortConfiguration('price', 'name');

// create sort object with the configuration
$sortArray = new SortArray($config);

// sort the array
$result = $sortArray->sort($products);

按对象排序

与按数组排序相同,但这里您可能有对象数组需要排序。例如,

$arrayOfObjects = [
    new Product('computer', 4),
    new Product('tv', 9),
    new Product('apple', 1),
    new Product('airpod', 1),
    new Product('airtag', 3),
    new Product('shampoo', 5)
];

如何

// create a configuration object specifying integer and string field accordingly.
$config = new SortConfiguration('price', 'name');

// create sort object with the configuration
$sortObject = new SortObject($config);

// sort the array
$result = $sortObject->sort($products);

开发

要运行测试用例,

composer run-script tests