abbasghasemi/collection

PHP 数组操作完整工具集合。

1.6 2024-08-19 19:53 UTC

This package is auto-updated.

Last update: 2024-09-19 20:10:03 UTC


README

PHP 数组操作库

强大

  • 支持列表、映射、集合、栈、队列、对象等...
  • 函数式(indexOf、map、where、reduce、first、firstOrNull firstWhere、...)
  • 类型泛型文档
  • 生成并填充列表的 Collections 类 Collections::filled(int $length, mixed $element)
  • 强制地图和列表接受特定类型的能力

安装

推荐通过 Composer 安装。运行以下命令安装包并将其添加到项目的 composer.json 文件中

composer require abbasghasemi/collection

数组示例

$list = Collections::filled(10, 'filled'); // ArrayList
echo count($list); // 10
echo Collections::toArraySet($list)->size(); // 1
$list->add(1); // This method does not exist!
echo $list->first(); // filled

$list = new MutableArrayList(/*[default]*/type: 'int');
$list->add(1); // added
$list->add(5); // added
echo count($list); // 2
echo $list->indexOf(1); // 0
echo $list->indexOf(6); // -1

$list = Collections::generate(10, function ($index){
    return $index;
}); // ArrayList
$list = $list->where(function ($element){
    return $element % 2 === 0;
});
echo $list->last(); // 8
echo $list; // [0,2,4,6,8]

映射示例

$map = new MutableInsensitiveMap();
$map['InSensitive'] = 'Insensitive';
$map['INSENSITIVE'] = 'Insensitive';
echo $map['insensitive']; // Insensitive
echo $map->size(); // 1

$object = new MutableArrayList(); // or other object
$map2 = new MutableObjectMap(keyType: $object::class, valueType: $map::class);
$map2[$object] = $map;

echo intval($map2[$object] === $map); // 1

$map2->values()->first()['INSENSITIVE'] = 10;
echo $map['InSensitive']; // 10
$map2->keys()->first()->add('first');
$map2->keys()->first()->add('last');

echo $object->join(','); // first,last

数组类

类方法

映射类

类方法

Collections 类

另见 easy-data-model

从数组数据创建数据模型。

作者 & 支持

该库由 Abbas Ghasemi 创建。

您可以在 GitHub Issue Tracker 报告问题。