awssat/ array-helper
PHP的灵活且强大的数组操作助手
Requires
- php: ~7.0
Requires (Dev)
- phpunit/phpunit: ^6.4
This package is auto-updated.
Last update: 2024-09-20 13:49:13 UTC
README
⚡️ PHP的灵活、简单且强大的数组操作助手。它提供了方法链的魔力,并将其包含在视图中变得更容易、更简洁。它支持大多数PHP内置数组函数
arr([' ', 'hi ', null, ' welcome'])->map('trim')->filter()->get() >> ['hi', 'welcome']
特性
- 支持所有PHP数组函数。
- 简短的方法名,无需编写"array_",例如array_map可以仅使用map(..)
- 数组项可以作为属性或键检索或更新 [->key 或 [key] ]
- 支持强大的条件方法。if、else、if{AnyMethod}、endif。
- 支持驼峰式和蛇形方法名。
- 有用的新方法,如equal、exists等。
安装/使用
您可以在项目文件夹中通过composer本地安装此包
$ composer require awssat/array-helper
安装后,只需开始使用助手arr([...])
或ArrayHelper::make([...])
示例
您可以使用任何数组函数,无需"array_",如果您喜欢,您可以使用它如array_filter或arrayFilter..所有都将工作。
$x = arr(['', 'item', null, 'item2'])->filter()->get() >> ['item', 'item2']
您可以使用条件,if(function() {...}),if{AnyMethod},else(),endif()
$x = arr(['item', 'item2', null]) ->ifContains(null) ->filter() ->endif() ->get()
您也可以使用带有if
的有用方法,如ifEmpty
、ifKeyExists
或ifEqual
等。
get()将返回所有项目,而get(index)将返回数组中的项目。all()是get(all, true)的别名,它将忽略条件并强制返回项目。
上面的示例可以使用all()简化如下
$x = arr(['item', 'item2', null]) ->ifContains(null) ->filter() ->all()
您可以使用do(callback)在数组上运行回调。
$x = arr(['item ', 'item2']) ->do(function() { return $this->map('trim'); }) ->all()
PHP内置的array_map、array_walk、array_filter和array_reduce是最佳的!
array_map可以遍历所有项目并更改它们。
$array->map(function($item) { return 'Hello: '. strip_tags($item) . ' !'; });
或对于简单的函数使用,$array->map('trim')
array_walk可用于遍历而不更改项目
$array->walk(function($item, $key) { print "$key: $item<br />\n"; });
或如果您想更改值
$array->walk(function(&$item, $key) { $item = $item * 2; });
array_filter非常适合过滤数组
$array->filter(function($item) { return $item > 5; });
或只需$array->filter()
来删除任何等于FALSE的值。
测试
简单使用
$ composer test
致谢
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。