solidworx / lodash-php
Requires
- php: ^7.2 || ^8.0
- sebastian/comparator: ^1.2 | ^2.0 | ^2.1 | ^3.0 | ^4.0 | ^5.0
- symfony/property-access: ^2.7 | ^3.0 | ^4.0 | ^5.0 | ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.12
- phpdocumentor/reflection-docblock: *
- phpstan/phpdoc-parser: *
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^7.3 || ^8.4
README
Lodash-PHP 是 Lodash JS 库到 PHP 的移植。它是一组易于使用的实用函数,适用于日常 PHP 项目。
Lodash-PHP 尽可能地模仿 lodash.js
需求
Lodash-PHP 至少需要 PHP 7.2+,但推荐使用最新版本的 PHP。
安装
通过 composer 安装 Lodash-PHP
$ composer require lodash-php/lodash-php
用法
Lodash-PHP 中的每个方法都是一个独立的函数,可以单独导入和使用。
<?php use function _\each; each([1, 2, 3], function (int $item) { var_dump($item); });
Lodash-PHP 还提供了一个全局的 _
类,可以全局使用。
<?php _::each([1, 2, 3], function (int $item) { var_dump($item); });
方法
数组
chunk
创建一个元素分组为 size
长度的数组。如果 array
不能均匀分割,最后一个分组将是剩余的元素。
参数
@param array $array 要处理的数组。
@param int $number [size=1] 每个分组的长度
返回
@return array 返回新的分组数组。
示例
<?php use function _\chunk; chunk(['a', 'b', 'c', 'd'], 2) // => [['a', 'b'], ['c', 'd']] chunk(['a', 'b', 'c', 'd'], 3) // => [['a', 'b', 'c'], ['d']]
compact
创建一个新数组,移除所有非真值。值 false
、null
、0
、""
、undefined
和 NaN
是非真值。
参数
@param array $array 要压缩的数组。
返回
@return array 返回新的筛选值数组。
示例
<?php use function _\compact; compact([0, 1, false, 2, '', 3]) // => [1, 2, 3]
concat
创建一个新数组,连接 array
与任何其他数组或值。
参数
@param array $array 要连接的数组。
@param array<int, mixed> $values 要连接的值。
返回
@return array 返回新的连接数组。
示例
<?php use function _\concat; $array = [1]; $other = concat($array, 2, [3], [[4]]); var_dump($other) // => [1, 2, 3, [4]] var_dump($array) // => [1]
difference
使用 SameValueZero
对比值创建一个不包含在其他给定数组中的 array
值数组。结果的顺序和引用由第一个数组确定。
注意:与 pullAll
不同,此方法返回一个新的数组。
参数
@param array $array 要检查的数组。
@param array ...$values 要排除的值。
返回
@return array 返回新的筛选值数组。
示例
<?php use function _\difference; difference([2, 1], [2, 3]) // => [1]
differenceBy
此方法类似于 difference
,但它接受 iteratee
,该迭代器为 array
和 values
中的每个元素调用,以生成比较的准则。结果的顺序和引用由第一个数组确定。迭代器以一个参数调用:(值)。
注意:与 pullAllBy
不同,此方法返回一个新的数组。
参数
@param array $array 要检查的数组。
@param array<int, mixed> ...$values 要排除的值。
@param callable $iteratee 每个元素调用的迭代器。
返回
@return array 返回新的筛选值数组。
示例
<?php use function _\differenceBy; differenceBy([2.1, 1.2], [2.3, 3.4], 'floor') // => [1.2]
differenceWith
此方法类似于 difference
,但它接受 comparator
,该比较器用于比较 array
中的元素和 values
。结果的顺序和引用由第一个数组确定。比较器以两个参数调用:(arrVal, othVal)。
注意:与 pullAllWith
不同,此方法返回一个新的数组。
参数
@param array<int, mixed> $array 要检查的数组。
@param array ...$values 要排除的值。
@param callable $comparator 每个元素调用的比较器。
返回
@return array 返回新的筛选值数组。
示例
<?php use function _\differenceWith; $objects = [[ 'x' => 1, 'y' => 2 ], [ 'x' => 2, 'y' => 1 ]] differenceWith($objects, [[ 'x' => 1, 'y' => 2 ]], '_::isEqual') // => [[ 'x' => 2, 'y' => 1 ]]
drop
创建一个从数组开头删除n
个元素的数组的切片。
注意:此函数将重新排序并重置数组索引
参数
@param array $array 要查询的数组。
@param int $n 要删除的元素数量。
返回
@return array 数组的切片。
示例
<?php use function _\drop; drop([1, 2, 3]) // => [2, 3] drop([1, 2, 3], 2) // => [3] drop([1, 2, 3], 5) // => [] drop([1, 2, 3], 0) // => [1, 2, 3]
dropRight
创建一个从数组末尾删除n
个元素的数组的切片。注意:此函数将重新排序并重置数组索引
参数
@param array $array 要查询的数组。
@param int $n 要删除的元素数量。
返回
@return array 数组的切片。
示例
<?php use function _\dropRight; dropRight([1, 2, 3]) // => [1, 2] dropRight([1, 2, 3], 2) // => [1] dropRight([1, 2, 3], 5) // => [] dropRight([1, 2, 3], 0) // => [1, 2, 3]
dropRightWhile
创建一个从数组末尾排除元素的数组的切片。元素将被删除,直到predicate
返回falsey。断言函数用三个参数调用:(value, index, array)。
参数
@param array $array 要查询的数组。
@param callable $predicate 每次迭代调用的函数。
返回
@return array 数组的切片。
示例
<?php use function _\dropRightWhile; $users = [ [ 'user' => 'barney', 'active' => false ], [ 'user' => 'fred', 'active' => true ], [ 'user' => 'pebbles', 'active' => true ] ] dropRightWhile($users, function($user) { return $user['active']; }) // => objects for ['barney']
dropWhile
创建一个从数组开头排除元素的数组的切片。元素将被删除,直到predicate
返回falsey。断言函数用三个参数调用:(value, index, array)。
参数
@param array $array 要查询的数组。
@param callable $predicate 每次迭代调用的函数。
返回
@return array 数组的切片。
示例
<?php use function _\dropWhile; $users = [ [ 'user' => 'barney', 'active' => true ], [ 'user' => 'fred', 'active' => true ], [ 'user' => 'pebbles', 'active' => false ] ] dropWhile($users, function($user) { return $user['active']; } ) // => objects for ['pebbles']
every
检查predicate
是否对array
的所有元素返回truthy。一旦predicate
返回falsey,迭代就会停止。断言函数用三个参数调用:(value, index, array)。
注意:此方法对于空数组返回true
,因为对于空数组的元素,任何东西都是真的。
参数
@param iterable $collection 要迭代的数组。
@param callable $predicate 每次迭代调用的函数。
返回
@return bool 如果所有元素通过断言检查,则返回true
,否则返回false
。
示例
<?php use function _\every; every([true, 1, null, 'yes'], function ($value) { return is_bool($value);}) // => false $users = [ ['user' => 'barney', 'age' => 36, 'active' => false], ['user' => 'fred', 'age' => 40, 'active' => false], ]; // The `matches` iteratee shorthand. $this->assertFalse(every($users, ['user' => 'barney', 'active' => false])); // false // The `matchesProperty` iteratee shorthand. $this->assertTrue(every($users, ['active', false])); // true // The `property` iteratee shorthand. $this->assertFalse(every($users, 'active')); //false
findIndex
此方法类似于find
,但返回的是断言返回truthy的第一个元素的索引,而不是元素本身。
参数
@param array $array 要检查的数组。
@param callable $predicate 每次迭代调用的函数。
@param int $fromIndex 搜索的起始索引。
返回
@return int 找到元素的索引,否则返回-1
。
示例
<?php use function _\findIndex; $users = [ ['user' => 'barney', 'active' => false], ['user' => 'fred', 'active' => false], ['user' => 'pebbles', 'active' => true], ]; findIndex($users, function($o) { return $o['user'] s== 'barney'; }); // => 0 // The `matches` iteratee shorthand. findIndex($users, ['user' => 'fred', 'active' => false]); // => 1 // The `matchesProperty` iteratee shorthand. findIndex($users, ['active', false]); // => 0 // The `property` iteratee shorthand. findIndex($users, 'active'); // => 2
findLastIndex
此方法类似于findIndex
,但它从右到左遍历collection
的元素。
参数
@param array $array 要检查的数组。
@param mixed $predicate 每次迭代调用的函数。
@param int $fromIndex 搜索的起始索引。
返回
@return int 找到元素的索引,否则返回-1
。
示例
<?php use function _\findLastIndex; $users = [ ['user' => 'barney', 'active' => true ], ['user' => 'fred', 'active' => false ], ['user' => 'pebbles', 'active' => false ] ] findLastIndex($users, function($user) { return $user['user'] === 'pebbles'; }) // => 2
flatten
将数组扁平化一层。
参数
@param array $array 要扁平化的数组。
返回
@return array 新的扁平化数组。
示例
<?php use function _\flatten; flatten([1, [2, [3, [4]], 5]]) // => [1, 2, [3, [4]], 5]
flattenDeep
递归扁平化数组。
参数
@param array $array 要扁平化的数组。
返回
@return array 返回新的扁平化数组。
示例
<?php use function _\flattenDeep; flattenDeep([1, [2, [3, [4]], 5]]); // => [1, 2, 3, 4, 5]
flattenDepth
递归扁平化数组直到depth
次。
参数
@param array $array 要扁平化的数组。
@param int $depth 最大的递归深度。
返回
@return array 新的扁平化数组。
示例
<?php use function _\flattenDepth; $array = [1, [2, [3, [4]], 5]] flattenDepth($array, 1) // => [1, 2, [3, [4]], 5] flattenDepth($array, 2) // => [1, 2, 3, [4], 5]
fromPairs
是toPairs
的逆操作,此方法返回一个由键值对组成的对象。
参数
@param array $pairs 键值对。
返回
@return \stdClass 新的对象。
示例
<?php use function _\fromPairs; fromPairs([['a', 1], ['b', 2]]) // => stdClass( // 'a' => 1, //'b' => 2, // )
head
获取数组的第一个元素。
参数
@param array $array 要查询的数组。
返回
@return mixed 返回数组的第一个元素。
示例
<?php use function _\head; head([1, 2, 3]) // => 1 head([]) // => null
indexOf
使用SameValueZero
进行等性比较,在数组中找到第一个value
的索引。如果fromIndex
为负数,则将其用作从数组末尾的偏移量。
参数
@param array $array 要检查的数组。
@param mixed $value 要搜索的值。
@param int $fromIndex 搜索的起始索引。
返回
@return int 匹配值的索引,否则返回-1
。
示例
<?php use function _\indexOf; indexOf([1, 2, 1, 2], 2) // => 1 // Search from the `fromIndex`. indexOf([1, 2, 1, 2], 2, 2) // => 3
initial
获取数组中除了最后一个元素之外的所有元素。
参数
@param array $array 要查询的数组。
返回
@return array 数组的切片。
示例
<?php use function _\initial; initial([1, 2, 3]) // => [1, 2]
intersection
使用SameValueZero
进行等性比较,创建一个包含所有给定数组中唯一值的数组。结果值的顺序和引用由第一个数组确定。
参数
@param array ...$arrays
返回
@return array 新的包含相交值的数组。
示例
<?php use function _\intersection; intersection([2, 1], [2, 3]) // => [2]
intersectionBy
此方法类似于intersection
,不同之处在于它接受iteratee
,该迭代器为每个arrays
中的元素调用,以生成比较的标准。结果的顺序和引用由第一个数组确定。迭代器用一个参数调用:(值)。
参数
@param array<int, mixed> ...$arrays
@param callable $iteratee 每个元素调用的迭代器。
返回
@return array 新的包含相交值的数组。
示例
<?php use function _\intersectionBy; intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor) // => [2.1] // The `property` iteratee shorthand. intersectionBy([[ 'x' => 1 ]], [[ 'x' => 2 ], [ 'x' => 1 ]], 'x'); // => [[ 'x' => 1 ]]
intersectionWith
此方法类似于intersection
,不同之处在于它接受comparator
,用于比较arrays
中的元素。结果的顺序和引用由第一个数组确定。比较器用两个参数调用:(arrVal, othVal)。
参数
@param array ...$arrays
@param callable $comparator 每个元素调用的比较器。
返回
@return array 新的包含相交值的数组。
示例
<?php use function _\intersectionWith; $objects = [[ 'x' => 1, 'y' => 2 ], [ 'x' => 2, 'y' => 1 ]] $others = [[ 'x' => 1, 'y' => 1 ], [ 'x' => 1, 'y' => 2 ]] intersectionWith($objects, $others, '_::isEqual') // => [[ 'x' => 1, 'y' => 2 ]]
last
获取array
的最后一个元素。
参数
@param array $array 要查询的数组。
返回
@return mixed 返回array
的最后一个元素。
示例
<?php use function _\last; last([1, 2, 3]) // => 3
lastIndexOf
此方法类似于indexOf
,不同之处在于它从右到左迭代array
中的元素。
参数
@param array $array 要检查的数组。
@param mixed $value 要搜索的值。
@param int $fromIndex 搜索的起始索引。
返回
@return int 匹配值的索引,否则返回-1
。
示例
<?php use function _\lastIndexOf; lastIndexOf([1, 2, 1, 2], 2) // => 3 // Search from the `fromIndex`. lastIndexOf([1, 2, 1, 2], 2, 2) // => 1
nth
获取array
中索引为n
的元素。如果n
为负,则返回从末尾开始的第n个元素。
参数
@param array $array 要查询的数组。
@param int $n 要返回的元素的索引。
返回
@return mixed 返回array
的第n个元素。
示例
<?php use function _\nth; $array = ['a', 'b', 'c', 'd'] nth($array, 1) // => 'b' nth($array, -2) // => 'c'
pull
使用SameValueZero
(http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)进行相等比较,从array
中删除所有给定值。
注意:与without
不同,此方法会修改array
。使用remove
通过谓词从数组中删除元素。
参数
@param array $array 要修改的数组。
@param array<int, string> $values 要删除的值。
返回
@return array
示例
<?php use function _\pull; $array = ['a', 'b', 'c', 'a', 'b', 'c'] pull($array, 'a', 'c') var_dump($array) // => ['b', 'b']
pullAll
此方法类似于pull
,但接受要删除值的数组。
注意:与difference
不同,此方法会修改array
。
参数
@param array $array 要修改的数组。
@param array $values 要删除的值。
返回
@return array array
。
示例
<?php use function _\pullAll; $array = ['a', 'b', 'c', 'a', 'b', 'c'] pullAll($array, ['a', 'c']) var_dump($array) // => ['b', 'b']
pullAllBy
此方法类似于pullAll
,但接受迭代器iteratee
,该迭代器为array
和values
中的每个元素调用,以生成比较的标准。迭代器用一个参数调用:(值)。
注意:与differenceBy
不同,此方法会修改array
。
参数
@param array $array 要修改的数组。
@param array $values 要删除的值。
@param callable $iteratee 每个元素调用的迭代器。
返回
@return array array
。
示例
<?php use function _\pullAllBy; $array = [[ 'x' => 1 ], [ 'x' => 2 ], [ 'x' => 3 ], [ 'x' => 1 ]] pullAllBy($array, [[ 'x' => 1 ], [ 'x' => 3 ]], 'x') var_dump($array) // => [[ 'x' => 2 ]]
pullAllWith
此方法类似于pullAll
,但接受比较器comparator
,用于比较array
中的元素与values
。比较器用两个参数调用:(arrVal, othVal)。
注意:与differenceWith
不同,此方法会修改array
。
参数
@param array $array 要修改的数组。
@param array $values 要删除的值。
@param callable $comparator 每个元素调用的比较器。
返回
@return array array
。
示例
<?php use function _\pullAllWith; $array = [[ 'x' => 1, 'y' => 2 ], [ 'x' => 3, 'y' => 4 ], [ 'x' => 5, 'y' => 6 ]] pullAllWith($array, [[ 'x' => 3, 'y' => 4 ]], '_\isEqual') var_dump($array) // => [[ 'x' => 1, 'y' => 2 ], [ 'x' => 5, 'y' => 6 ]]
pullAt
删除与indexes
对应的array
元素,并返回被删除元素的新数组。
注意:与at
不同,此方法会修改array
。
参数
@param array $array 要修改的数组。
@param (int | int[]) $indexes 要删除的元素的索引。
返回
@return array 被删除元素的新数组。
示例
<?php use function _\pullAt; $array = ['a', 'b', 'c', 'd'] $pulled = pullAt($array, [1, 3]) var_dump($array) // => ['a', 'c'] var_dump($pulled) // => ['b', 'd']
remove
从array
中删除所有使predicate
返回真值的元素,并返回被删除元素的数组。谓词用三个参数调用:(value, index, array)。
注意:与filter
不同,此方法会修改array
。使用pull
通过值从数组中提取元素。
参数
@param array $array 要修改的数组。
@param callable $predicate 每次迭代调用的函数。
返回
@return array 被删除元素的新数组。
示例
<?php use function _\remove; $array = [1, 2, 3, 4] $evens = remove($array, function ($n) { return $n % 2 === 0; }) var_dump($array) // => [1, 3] var_dump($evens) // => [2, 4]
sample
从array
中获取一个随机元素。
参数
@param array $array 要从中抽取的数组。
返回
@return mixed 返回随机元素。
示例
<?php use function _\sample; sample([1, 2, 3, 4]) // => 2
sampleSize
从array
中获取n个随机元素,直到达到array
的大小。
参数
@param array $array 要从中抽取的数组。
@param int $n 要抽取的元素数量。
返回
@return array 随机元素。
示例
<?php use function _\sampleSize; sampleSize([1, 2, 3], 2) // => [3, 1] sampleSize([1, 2, 3], 4) // => [2, 3, 1]
shuffle
创建一个打乱顺序的值数组。
参数
@param array $array 要打乱的数组。
返回
@return array 新的打乱顺序的数组。
示例
<?php use function _\shuffle; shuffle([1, 2, 3, 4]) // => [4, 1, 3, 2]
切片
从 start
到 end
(不包括 end
)创建 array
的一个切片。
参数
@param array $array 要切片的数组。
@param int $start 起始位置。
@param int $end 结束位置。
返回
@return array 数组的切片。
尾部
获取 array
的除了第一个元素之外的所有元素。
参数
@param array $array 要查询的数组。
返回
@return array 数组的切片。
示例
<?php use function _\tail; tail([1, 2, 3]) // => [2, 3]
取前
从数组开头创建包含 n
个元素的切片。
参数
@param array $array 要查询的数组。
@param int $n 要取的元素数量。
返回
@return array 数组的切片。
示例
<?php use function _\take; take([1, 2, 3]) // => [1] take([1, 2, 3], 2) // => [1, 2] take([1, 2, 3], 5) // => [1, 2, 3] take([1, 2, 3], 0) // => []
取后
从数组末尾创建包含 n
个元素的切片。
参数
@param array $array 要查询的数组。
@param int $n 要取的元素数量。
返回
@return array 数组的切片。
示例
<?php use function _\takeRight; takeRight([1, 2, 3]) // => [3] takeRight([1, 2, 3], 2) // => [2, 3] takeRight([1, 2, 3], 5) // => [1, 2, 3] takeRight([1, 2, 3], 0) // => []
取后直到
从数组末尾创建一个切片,直到 predicate
返回 falsy。谓词使用三个参数调用:(值,索引,数组)。
参数
@param array $array 要查询的数组。
@param callable $predicate 每次迭代调用的函数。
返回
@return array 数组的切片。
示例
<?php use function _\takeRightWhile; $users = [ [ 'user' => 'barney', 'active' => false ], [ 'user' => 'fred', 'active' => true ], [ 'user' => 'pebbles', 'active' => true ] ]; takeRightWhile($users, function($value) { return $value['active']; }) // => objects for ['fred', 'pebbles']
取前直到
从数组开头创建一个切片,直到 predicate
返回 falsy。谓词使用三个参数调用:(值,索引,数组)。
参数
@param array $array 要查询的数组。
@param mixed $predicate 每次迭代调用的函数。
返回
@return array 数组的切片。
示例
<?php use function _\takeWhile; $users = [ [ 'user' => 'barney', 'active' => true ], [ 'user' => 'fred', 'active' => true ], [ 'user' => 'pebbles', 'active' => false ] ] takeWhile($users, function($value) { return $value['active']; }) // => objects for ['barney', 'fred']
并集
使用 SameValueZero
进行相等比较,从所有给定数组中按顺序创建一个包含唯一值的数组。
参数
@param array ...$arrays 要检查的数组。
返回
@return array 合并后的新数组。
示例
<?php use function _\union; union([2], [1, 2]) // => [2, 1]
并集通过
此方法类似于 union
,但它接受 iteratee
,它对每个数组的每个元素进行调用,以生成唯一性计算的依据。结果值从第一个出现该值的数组中选择。iteratee 使用一个参数调用:(值)。
参数
@param array<int, mixed> ...$arrays 要检查的数组。
@param callable $iteratee 每个元素调用的迭代器。
返回
@return array 合并后的新数组。
示例
<?php use function _\unionBy; unionBy([2.1], [1.2, 2.3], 'floor') // => [2.1, 1.2] // The `_::property` iteratee shorthand. unionBy([['x' => 1]], [['x' => 2], ['x' => 1]], 'x'); // => [['x' => 1], ['x' => 2]]
并集与
此方法类似于 union
,但它接受 comparator
,它用于比较数组的元素。结果值从第一个出现该值的数组中选择。comparator 使用两个参数调用:(arrVal,othVal)。
参数
@param array<int, mixed> ...$arrays 要检查的数组。
@param callable $comparator 每个元素调用的比较器。
返回
@return array 合并后的新数组。
示例
<?php use function _\unionWith; $objects = [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1]] $others = [['x' => 1, 'y' => 1], ['x' => 1, 'y' => 2]] unionWith($objects, $others, '_::isEqual') // => [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1], ['x' => 1, 'y' => 1]]
去重
使用 SameValueZero
进行相等比较,创建一个数组的不重复版本,其中仅保留每个元素的第一次出现。结果值的顺序由它们在数组中出现的顺序决定。
参数
@param array $array 要检查的数组。
返回
@return array 新的不重复数组。
示例
<?php use function _\uniq; uniq([2, 1, 2]) // => [2, 1]s
去重通过
此方法类似于 uniq
,但它接受 iteratee
,它对数组中的每个元素进行调用,以生成唯一性计算的依据。结果值的顺序由它们在数组中出现的顺序决定。iteratee 使用一个参数调用:(值)。
参数
@param array $array 要检查的数组。
@param mixed $iteratee 每个元素调用的迭代器。
返回
@return array 新的不重复数组。
示例
<?php use function _\uniqBy; uniqBy([2.1, 1.2, 2.3], 'floor') // => [2.1, 1.2]
去重与
此方法类似于 uniq
,但它接受 comparator
,它用于比较数组中的元素。结果值的顺序由它们在数组中出现的顺序决定。comparator 使用两个参数调用:(arrVal,othVal)。
参数
@param array $array 要检查的数组。
@param callable $comparator 每个元素调用的比较器。
返回
@return array 新的不重复数组。
示例
<?php use function _\uniqWith; $objects = [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1], ['x' => 1, 'y' => 2]] uniqWith($objects, '_::isEqual') // => [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1]]
解包
此方法类似于 zip
,但它接受一个分组元素的数组,并创建一个数组,将元素重新分组到它们之前的配置。
参数
@param array $array 要处理的分组元素数组。
返回
@return array 重新分组的元素的新数组。
示例
<?php use function _\unzip; $zipped = zip(['a', 'b'], [1, 2], [true, false]) // => [['a', 1, true], ['b', 2, false]] unzip($zipped) // => [['a', 'b'], [1, 2], [true, false]]
解包与
此方法类似于 unzip
,但它接受 iteratee
来指定如何组合重新分组的值。iteratee 使用每个分组的元素调用:(...group)。
参数
@param array $array 要处理的分组元素数组。
@param (callable | null) $iteratee 结合重新分组值的函数。
返回
@return array 重新分组的元素的新数组。
示例
<?php use function _\unzipWith; $zipped = zip([1, 2], [10, 20], [100, 200]) // => [[1, 10, 100], [2, 20, 200]] unzipWith(zipped, '_::add') // => [3, 30, 300]
排除
使用 SameValueZero
进行相等比较,创建一个排除所有给定值的数组。
注意:与 pull
不同,此方法返回一个新数组。
参数
@param array $array 要检查的数组。
@param array
返回
@return array 过滤后的新数组。
示例
<?php use function _\without; without([2, 1, 2, 3], 1, 2) // => [3]
zip
创建一个包含分组元素的数组,其中第一个数组包含给定数组的第一个元素,第二个数组包含给定数组的第二个元素,依此类推。
参数
@param array ...$arrays 要处理的数组。
返回
@return array 分组元素的新数组。
示例
<?php use function _\zip; zip(['a', 'b'], [1, 2], [true, false]) // => [['a', 1, true], ['b', 2, false]]
zipObject
此方法类似于 fromPairs
,但它接受两个数组,一个是属性标识符数组,另一个是对应的值数组。
参数
@param array $props 属性标识符。
@param array $values 属性值。
返回
@return object 新对象。
示例
<?php use function _\zipObject; zipObject(['a', 'b'], [1, 2]) /* => object(stdClass)#210 (2) { ["a"] => int(1) ["b"] => int(2) } *\/
zipObjectDeep
此方法类似于 zipObject
,但它支持属性路径。
参数
@param array $props 属性标识符。
@param array $values 属性值。
返回
@return \stdClass 新的对象。
示例
<?php use function _\zipObjectDeep; zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]) /* => class stdClass#20 (1) { public $a => class stdClass#19 (1) { public $b => array(2) { [0] => class stdClass#17 (1) { public $c => int(1) } [1] => class stdClass#18 (1) { public $d => int(2) } } } } *\/
zipWith
此方法类似于 zip
,但它接受 iteratee
以指定如何组合分组值。迭代器与每个组中的元素一起调用:(…group)。
参数
@param array
@param callable $iteratee 组合分组值的函数。
返回
@return array 分组元素的新数组。
示例
<?php use function _\zipWith; zipWith([1, 2], [10, 20], [100, 200], function($a, $b, $c) { return $a + $b + $c; }) // => [111, 222]
集合
countBy
创建一个由 collection
中每个元素通过 iteratee
运行生成的键组成的数组。每个键的对应值是键通过 iteratee
返回的次数。迭代器使用一个参数调用:(value)。
参数
@param iterable $collection 要迭代的集合。
@param callable $iteratee 转换键的迭代器。
返回
@return array 返回组成的聚合对象。
示例
<?php use function _\countBy; countBy([6.1, 4.2, 6.3], 'floor'); // => ['6' => 2, '4' => 1] // The `property` iteratee shorthand. countBy(['one', 'two', 'three'], 'strlen'); // => ['3' => 2, '5' => 1]
each
迭代 collection
的元素并对每个元素调用 iteratee
。迭代器使用三个参数调用:(value, index|key, collection)。迭代器函数可以通过显式返回 false
来提前退出迭代。
注意:与其他“集合”方法一样,具有“length”属性的对象像数组一样迭代。为了避免这种行为,使用 forIn
或 forOwn
进行对象迭代。
参数
@param (array | iterable | object) $collection 要迭代的集合。
@param callable $iteratee 每次迭代调用的函数。
返回
@return (array | object) 返回 collection
。
示例
<?php use function _\each; each([1, 2], function ($value) { echo $value; }) // => Echoes `1` then `2`. each((object) ['a' => 1, 'b' => 2], function ($value, $key) { echo $key; }); // => Echoes 'a' then 'b' (iteration order is not guaranteed).
eachRight
此方法类似于 each
,但它从右向左迭代 collection
的元素。
参数
@param (array | iterable | object) $collection 要迭代的集合。
@param callable $iteratee 每次迭代调用的函数。
返回
@return (array | object) 返回 collection
。
示例
<?php use function _\eachRight; eachRight([1, 2], function($value) { echo $value; }) // => Echoes `2` then `1`.
filter
迭代 array
的元素,返回返回真值的所有元素的数组。谓词使用三个参数调用:(value, index, array)。
注意:与 remove
不同,此方法返回一个新数组。
参数
@param iterable $array 要迭代的数组。
@param callable $predicate 每次迭代调用的函数。
返回
@return array 新的过滤数组。
示例
<?php use function _\filter; $users = [ [ 'user' => 'barney', 'age' => 36, 'active' => true], [ 'user' => 'fred', 'age' => 40, 'active' => false] ]; filter($users, function($o) { return !$o['active']; }); // => objects for ['fred'] // The `matches` iteratee shorthand. filter($users, ['age' => 36, 'active' => true]); // => objects for ['barney'] // The `matchesProperty` iteratee shorthand. filter($users, ['active', false]); // => objects for ['fred'] // The `property` iteratee shorthand. filter($users, 'active'); // => objects for ['barney']
find
迭代 collection
的元素,返回返回真值的第一个元素。谓词使用三个参数调用:(value, index|key, collection)。
参数
@param iterable $collection 要检查的集合。
@param callable $predicate 每次迭代调用的函数。
@param int $fromIndex 搜索的起始索引。
返回
@return mixed 返回匹配的元素,否则返回 null
。
示例
<?php use function _\find; $users = [ ['user' => 'barney', 'age' => 36, 'active' => true], ['user' => 'fred', 'age' => 40, 'active' => false], ['user' => 'pebbles', 'age' => 1, 'active' => true] ]; find($users, function($o) { return $o['age'] < 40; }); // => object for 'barney' // The `matches` iteratee shorthand. find($users, ['age' => 1, 'active' => true]); // => object for 'pebbles' // The `matchesProperty` iteratee shorthand. find($users, ['active', false]); // => object for 'fred' // The `property` iteratee shorthand. find($users, 'active'); // => object for 'barney'
findLast
此方法类似于 find
,但它从右向左迭代 collection
的元素。
参数
@param iterable $collection 要检查的集合。
@param callable $predicate 每次迭代调用的函数。
@param int $fromIndex 搜索的起始索引。
返回
@return mixed 返回匹配的元素,否则返回 undefined
。
示例
<?php use function _\findLast; findLast([1, 2, 3, 4], function ($n) { return $n % 2 == 1; }) // => 3
flatMap
通过运行 collection
中每个元素通过 iteratee
运行并展平映射结果来创建值的展平数组。迭代器使用三个参数调用:(value, index|key, collection)。
参数
@param iterable $collection 要迭代的集合。
@param callable $iteratee 每次迭代调用的函数。
返回
@return array 新的扁平化数组。
示例
<?php use function _\flatMap; function duplicate($n) { return [$n, $n] } flatMap([1, 2], 'duplicate') // => [1, 1, 2, 2]
flatMapDeep
此方法类似于 flatMap
,但它递归地展平映射结果。
参数
@param iterable $collection 要迭代的集合。
@param callable $iteratee 每次迭代调用的函数。
返回
@return array 返回新的扁平化数组。
示例
<?php use function _\flatMapDeep; function duplicate($n) { return [[[$n, $n]]]; } flatMapDeep([1, 2], 'duplicate'); // => [1, 1, 2, 2]
flatMapDepth
此方法类似于 flatMap
,但它递归地展平映射结果,最多 depth
次。
参数
@param iterable $collection 要迭代的集合。
@param callable $iteratee 每次迭代调用的函数。
@param int $depth 最大的递归深度。
返回
@return array 新的扁平化数组。
示例
<?php use function _\flatMapDepth; function duplicate($n) { return [[[$n, $n]]] } flatMapDepth([1, 2], 'duplicate', 2) // => [[1, 1], [2, 2]]
groupBy
通过将collection
中的每个元素运行通过iteratee
来创建一个数组,该数组由生成的键组成。分组值的顺序由它们在collection
中出现的顺序确定。每个键的对应值是由生成键的元素数组。iteratee使用一个参数调用:(value)。
参数
@param iterable $collection 要迭代的集合。
@param callable $iteratee 转换键的迭代器。
返回
@return array 返回组成的聚合对象。
示例
<?php use function _\groupBy; groupBy([6.1, 4.2, 6.3], 'floor'); // => ['6' => [6.1, 6.3], '4' => [4.2]] groupBy(['one', 'two', 'three'], 'strlen'); // => ['3' => ['one', 'two'], '5' => ['three']]
invokeMap
调用collection
中每个元素的path
方法,返回每个调用方法的结果数组。为每个调用方法提供任何额外的参数。如果path
是一个函数,它将为collection
中的每个元素调用,并将this
绑定到每个元素。
参数
@param iterable $collection 要迭代的集合。
@param (数组 | 可调用 | 字符串) $path 要调用的方法或每次迭代调用的函数的路径。
@param 数组 $args 调用每个方法时使用的参数。
返回
@return 数组 结果的数组。
示例
<?php use function _\invokeMap; invokeMap([[5, 1, 7], [3, 2, 1]], function($result) { sort($result); return $result;}) // => [[1, 5, 7], [1, 2, 3]] invokeMap([123, 456], 'str_split') // => [['1', '2', '3'], ['4', '5', '6']]
keyBy
通过将collection
中的每个元素运行通过iteratee
来创建一个对象,该对象由生成的键组成。每个键的对应值是负责生成键的最后元素。iteratee使用一个参数调用:(value)。
参数
@param iterable $collection 要迭代的集合。
@param callable $iteratee 转换键的迭代器。
返回
@return 数组 组成的聚合对象。
示例
<?php use function _\keyBy; $array = [ ['direction' => 'left', 'code' => 97], ['direction' => 'right', 'code' => 100], ]; keyBy($array, function ($o) { return \chr($o['code']); }) // => ['a' => ['direction' => 'left', 'code' => 97], 'd' => ['direction' => 'right', 'code' => 100]] keyBy($array, 'direction'); // => ['left' => ['direction' => 'left', 'code' => 97], 'right' => ['direction' => 'right', 'code' => 100]]
map
通过运行collection
中的每个元素通过iteratee
来创建一个值数组。iteratee使用三个参数调用:(value, index|key, collection)。
许多lodash-php方法被保护以作为类似于_::every
、_::filter
、_::map
、_::mapValues
、_::reject
和_::some
的方法的iteratee。
受保护的方法包括:ary
、chunk
、curry
、curryRight
、drop
、dropRight
、every
、fill
、invert
、parseInt
、random
、range
、rangeRight
、repeat
、sampleSize
、slice
、some
、sortBy
、split
、take
、takeRight
、template
、trim
、trimEnd
、trimStart
和words
参数
@param (数组 | 对象) $collection 要迭代的集合。
@param (可调用 | 字符串 | 数组) $iteratee 每次迭代调用的函数。
返回
@return 数组 返回新的映射数组。
示例
<?php use function _\map; function square(int $n) { return $n * $n; } map([4, 8], $square); // => [16, 64] map((object) ['a' => 4, 'b' => 8], $square); // => [16, 64] (iteration order is not guaranteed) $users = [ [ 'user' => 'barney' ], [ 'user' => 'fred' ] ]; // The `property` iteratee shorthand. map($users, 'user'); // => ['barney', 'fred']
orderBy
此方法类似于sortBy
,但允许指定排序迭代的顺序。如果未指定orders
,则按升序对所有值进行排序。否则,指定为“desc”以进行降序排序或“asc”以进行升序排序。
参数
@param (可迭代 | null) $collection 要迭代的集合。
@param (数组[] | 可调用[] | 字符串[]) $iteratee 要排序的迭代器。
@param 字符串[] $orders iteratees
的排序顺序。
返回
@return 数组 新的排序数组。
示例
<?php use function _\orderBy; $users = [ ['user' => 'fred', 'age' => 48], ['user' => 'barney', 'age' => 34], ['user' => 'fred', 'age' => 40], ['user' => 'barney', 'age' => 36] ] // Sort by `user` in ascending order and by `age` in descending order. orderBy($users, ['user', 'age'], ['asc', 'desc']) // => [['user' => 'barney', 'age' => 36], ['user' => 'barney', 'age' => 34], ['user' => 'fred', 'age' => 48], ['user' => 'fred', 'age' => 40]]
partition
创建一个数组,将元素分成两组,第一组包含predicate
返回真值的元素,第二组包含predicate
返回假值的元素。谓词使用一个参数调用:(value)。
参数
@param iterable $collection 要迭代的集合。
@param callable $predicate 每次迭代调用的函数。
返回
@return 数组 分组的元素数组。
示例
<?php use function _\partition; $users = [ ['user' => 'barney', 'age' => 36, 'active' => false], ['user' => 'fred', 'age' => 40, 'active' => true], ['user' => 'pebbles', 'age' => 1, 'active' => false] ]; partition($users, function($user) { return $user['active']; }) // => objects for [['fred'], ['barney', 'pebbles']]
reduce
将collection
减少到一个值,该值是运行每个元素通过iteratee
的累积结果,其中每次连续调用都提供前一次的返回值。如果没有给出accumulator
,则使用collection
的第一个元素作为初始值。iteratee使用四个参数调用:(accumulator, value, index|key, collection)。
许多lodash方法被保护以作为类似于reduce
、reduceRight
和transform
的方法的iteratee。
受保护的方法包括:assign
、defaults
、defaultsDeep
、includes
、merge
、orderBy
和sortBy
参数
@param iterable $collection 要迭代的集合。
@param 混合 $iteratee 每次迭代调用的函数。
@param 混合 $accumulator 初始值。
返回
@return 混合 返回累积的值。
示例
<?php use function _\reduce; reduce([1, 2], function($sum, $n) { return $sum + $n; }, 0) // => 3 reduce(['a' => 1, 'b' => 2, 'c' => 1], function ($result, $value, $key) { if (!isset($result[$value])) { $result[$value] = []; } $result[$value][] = $key; return $result; }, []) // => ['1' => ['a', 'c'], '2' => ['b']] (iteration order is not guaranteed)
reduceRight
这种方法类似于 reduce
,但它是从右到左遍历 collection
的元素。
参数
@param iterable $collection 要迭代的集合。
@param 混合 $iteratee 每次迭代调用的函数。
@param 混合 $accumulator 初始值。
返回
@return 混合 返回累积的值。
示例
<?php use function _\reduceRight; $array = [[0, 1], [2, 3], [4, 5]]; reduceRight(array, (flattened, other) => flattened.concat(other), []) // => [4, 5, 2, 3, 0, 1]
reject
与 filter
相反,此方法返回 collection
中那些 predicate
不返回 truthy 的元素。
参数
@param iterable $collection 要迭代的集合。
@param callable $predicate 每次迭代调用的函数。
返回
@return array 新的过滤数组。
示例
<?php use function _\reject; $users = [ ['user' => 'barney', 'active' => true], ['user' => 'fred', 'active' => false] ] reject($users, 'active') // => objects for ['fred']
size
通过返回数组的长度或对象的公共属性数量来获取 collection
的大小。
参数
@param (array | object | string) $collection 要检查的集合。
返回
@return int 返回集合的大小。
示例
<?php use function _\size; size([1, 2, 3]); // => 3 size(new class { public $a = 1; public $b = 2; private $c = 3; }); // => 2 size('pebbles'); // => 7
some
检查 predicate
是否对 collection
中的任何元素返回 truthy。一旦 predicate
返回 truthy,迭代就停止。断言以三个参数调用:(值,索引|键,集合)。
参数
@param iterable $collection 要迭代的集合。
@param (callable | string | array) $predicate 每次迭代调用的函数。
返回
@return boolean 如果任何元素通过断言检查,则返回 true
,否则返回 false
。
示例
<?php use function _\some; some([null, 0, 'yes', false], , function ($value) { return \is_bool($value); })); // => true $users = [ ['user' => 'barney', 'active' => true], ['user' => 'fred', 'active' => false] ]; // The `matches` iteratee shorthand. some($users, ['user' => 'barney', 'active' => false ]); // => false // The `matchesProperty` iteratee shorthand. some($users, ['active', false]); // => true // The `property` iteratee shorthand. some($users, 'active'); // => true
sortBy
通过将集合中的每个元素通过每个迭代器运行来创建一个元素数组,按升序排序。该方法执行稳定的排序,即它保留了相等元素的原排序顺序。迭代器以一个参数调用:(值)。
参数
@param (array | object | null) $collection 要迭代的集合。
@param (callable | callable[]) $iteratees 要按其排序的迭代器。
返回
@return array 返回新的排序数组。
示例
<?php use function _\sortBy; $users = [ [ 'user' => 'fred', 'age' => 48 ], [ 'user' => 'barney', 'age' => 36 ], [ 'user' => 'fred', 'age' => 40 ], [ 'user' => 'barney', 'age' => 34 ], ]; sortBy($users, [function($o) { return $o['user']; }]); // => [['user' => 'barney', 'age' => 36], ['user' => 'barney', 'age' => 34], ['user' => 'fred', 'age' => 48], ['user' => 'fred', 'age' => 40]] sortBy($users, ['user', 'age']); // => [['user' => 'barney', 'age' => 34], ['user' => 'barney', 'age' => 36], ['user' => 'fred', 'age' => 40], ['user' => 'fred', 'age' => 48]]
日期
now
获取自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来的毫秒数。
参数
返回
@return int 返回时间戳。
示例
<?php use function _\now; now(); // => 1511180325735
函数
after
与 before
相反;此方法创建一个函数,在它被调用 n
或更多次后调用 func
。
参数
@param int $n 在调用 func
之前要调用的次数。
@param Callable $func 要限制的函数。
返回
@return Callable 返回新的限制函数。
示例
<?php use function _\after; $saves = ['profile', 'settings']; $done = after(count($saves), function() { echo 'done saving!'; }); forEach($saves, function($type) use($done) { asyncSave([ 'type' => $type, 'complete' => $done ]); }); // => Prints 'done saving!' after the two async saves have completed.
ary
创建一个函数,它调用 func
,最多 n
个参数,忽略任何额外的参数。
参数
@param callable $func 要限制参数的函数。
@param int $n 参数限制。
返回
@return Callable 返回新的限制函数。
示例
<?php use function _\ary; map(['6', '8', '10'], ary('intval', 1)); // => [6, 8, 10]
before
创建一个函数,在它被调用少于 n
次时调用 func
,并带有创建函数的参数。后续调用创建的函数返回最后一次 func
调用的结果。
参数
@param int $n func
停止调用的调用次数。
@param callable $func 要限制的函数。
返回
@return callable 返回新的限制函数。
示例
<?php use function _\before; $users = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $result = uniqBy(map($users, before(5, [$repository, 'find'])), 'id') // => Fetch up to 4 results.
bind
创建一个函数,它使用 object
的 this
绑定和 partials
预先附加到它收到的参数来调用 func
。
参数
@param callable $function 要绑定的函数。
@param (object | mixed) $object func
的 object
绑定。
@param array<int, mixed> $partials 要部分应用的参数。
返回
@return callable 返回新的绑定函数。
示例
<?php use function _\bind; function greet($greeting, $punctuation) { return $greeting . ' ' . $this->user . $punctuation; } $object = $object = new class { public $user = 'fred'; }; $bound = bind('greet', $object, 'hi'); $bound('!'); // => 'hi fred!'
bindKey
创建一个函数,它使用 partials
预先附加到它收到的参数来调用 object
的 $function
方法。
此方法与 bind
不同,因为它允许绑定函数引用可能已重新定义或尚未存在的函数。
参数
@param object $object 在其上调用方法的对象。
@param string $function 方法的名称。
@param array<int, mixed> $partials 要部分应用的参数。
返回
@return callable 返回新的绑定函数。
示例
<?php use function _\bindKey; $object = new class { private $user = 'fred'; function greet($greeting, $punctuation) { return $greeting.' '.$this->user.$punctuation; } }; $bound = bindKey($object, 'greet', 'hi'); $bound('!'); // => 'hi fred!'
curry
创建一个接受 func
的参数的函数,如果已提供至少 arity
个参数,则调用 func
返回其结果,或者返回一个接受剩余 func
参数的函数,依此类推。如果 func.length
不足够,可以指定 func
的 arity
。
在单体构建中,_.curry.placeholder
的值默认为 _
,可以用作提供参数的占位符。
注意:此方法不设置 curried 函数的 "length" 属性。
参数
@param callable $func 需要柯里化的函数。
@param (int | null) $arity 函数 func
的arity。
返回
@return callable 返回新的柯里化函数。
示例
<?php use function _\curry; $abc = function($a, $b, $c) { return [$a, $b, $c]; }; $curried = curry($abc); $curried(1)(2)(3); // => [1, 2, 3] $curried(1, 2)(3); // => [1, 2, 3] $curried(1, 2, 3); // => [1, 2, 3] // Curried with placeholders. $curried(1)(_, 3)(2); // => [1, 2, 3]
delay
在 wait
毫秒后调用 func
。任何额外的参数将在调用 func
时提供给它。
参数
@param callable $func 需要延迟调用的函数。
@param int $wait 延迟调用的毫秒数。
@param array<int, mixed> $args
返回
@return int 返回定时器ID。
示例
<?php use function _\delay; delay(function($text) { echo $text; }, 1000, 'later'); // => Echo 'later' after one second.
flip
创建一个函数,该函数以反转的参数顺序调用 func
。
参数
@param callable $func 需要翻转参数的函数。
返回
@return callable 返回新的翻转函数。
示例
<?php use function _\flip; $flipped = flip(function() { return func_get_args(); }); flipped('a', 'b', 'c', 'd'); // => ['d', 'c', 'b', 'a']
memoize
创建一个函数,该函数会缓存 func
的结果。如果提供了 resolver
,它将根据缓存函数提供的参数确定存储结果的缓存键。默认情况下,缓存键使用缓存函数提供的第一个参数。
注意: 缓存作为缓存函数的 cache
属性公开。其创建可以通过用实现 Map
方法接口的 clear
、delete
、get
、has
和 set
的实例替换 _.memoize.Cache
构造函数来自定义。
参数
@param callable $func 需要缓存输出的函数。
@param (callable | null) $resolver 确定缓存键的函数。
返回
@return callable 返回新的缓存函数。
示例
<?php use function _\memoize; $object = ['a' => 1, 'b' => 2]; $other = ['c' => 3, 'd' => 4]; $values = memoize('_\values'); $values($object); // => [1, 2] $values($other); // => [3, 4] $object['a'] = 2; $values($object); // => [1, 2] // Modify the result cache. $values->cache->set($object, ['a', 'b']); $values($object); // => ['a', 'b']
negate
创建一个函数,该函数将否定谓词 func
的结果。
参数
@param callable $predicate 需要否定的谓词。
返回
@return callable 返回新的否定函数。
示例
<?php use function _\negate; function isEven($n) { return $n % 2 == 0; } filter([1, 2, 3, 4, 5, 6], negate($isEven)); // => [1, 3, 5]
once
创建一个函数,该函数仅调用一次 func
。重复调用该函数将返回第一次调用的值。该函数使用创建函数的参数调用 func
。
参数
@param callable $func 要限制的函数。
返回
@return callable 返回新的限制函数。
示例
<?php use function _\once; $initialize = once('createApplication'); $initialize(); $initialize(); // => `createApplication` is invoked once
overArgs
创建一个函数,该函数将转换后的参数调用 func
。
参数
@param callable $func 要包装的函数。
@param callable[] $transforms 参数转换。
返回
@return callable 返回新的函数。
示例
<?php use function _\overArgs; function doubled($n) { return $n * 2; } function square($n) { return $n * $n; } $func = overArgs(function($x, $y) { return [$x, $y]; }, ['square', 'doubled']); $func(9, 3); // => [81, 6] $func(10, 5); // => [100, 10]
partial
创建一个函数,该函数将 partials
预先附加到接收到的参数上,然后调用 func
。
参数
@param callable $func 要部分应用参数的函数。
@param array<int, mixed> $partials 要部分应用的参数。
返回
@return callable 返回新的部分应用函数。
示例
<?php use function _\partial; function greet($greeting, $name) { return $greeting . ' ' . $name; } $sayHelloTo = partial('greet', 'hello'); $sayHelloTo('fred'); // => 'hello fred'
rest
创建一个函数,该函数使用创建函数的 this
绑定和从 start
位置开始的参数数组调用 func
。
参数
@param callable $func 要应用剩余参数的函数。
@param (int | null) $start 剩余参数的起始位置。
返回
@return callable 返回新的函数。
示例
<?php use function _\rest; $say = rest(function($what, $names) { return $what . ' ' . implode(', ', initial($names)) . (size($names) > 1 ? ', & ' : '') . last($names); }); $say('hello', 'fred', 'barney', 'pebbles'); // => 'hello fred, barney, & pebbles'
spread
创建一个函数,该函数使用创建函数的 this
绑定和类似于 Function#apply
的参数数组调用 func
。
注意: 此方法基于 展开运算符。
参数
@param callable $func 要展开参数的函数。
@param int $start 展开的起始位置。
返回
@return callable 返回新的函数。
示例
<?php use function _\spread; $say = spread(function($who, $what) { return $who . ' says ' . $what; }); $say(['fred', 'hello']); // => 'fred says hello'
unary
创建一个函数,该函数最多接受一个参数,忽略任何额外的参数。
参数
@param callable $func 要限制参数的函数。
返回
@return callable 返回新的受限函数。
示例
<?php use function _\unary; map(['6', '8', '10'], unary('intval')); // => [6, 8, 10]
wrap
创建一个函数,该函数将 value
作为第一个参数提供给 wrapper
。函数提供的任何其他参数都附加到提供给 wrapper
的参数上。
参数
@param mixed $value 需要包装的值。
@param callable $wrapper 包装函数。
返回
@return callable 返回新的函数。
示例
<?php use function _\wrap; $p = wrap('_\escape', function($func, $text) { return '<p>' . $func($text) . '</p>'; }); $p('fred, barney, & pebbles'); // => '<p>fred, barney, & pebbles</p>'
语言
eq
比较两个值以确定它们是否相等。
参数
@param mixed $value 要比较的值。
@param mixed $other 要比较的另一个值。
返回
@return boolean 如果值相等,则返回 true
,否则返回 false
。
示例
<?php use function _\eq; $object = (object) ['a' => 1]; $other = (object) ['a' => 1]; eq($object, $object); // => true eq($object, $other); // => false eq('a', 'a'); // => true eq(['a'], (object) ['a']); // => false eq(INF, INF); // => true
isEqual
对两个值执行深度比较以确定它们是否相等。
注意:此方法支持比较数组、布尔值、DateTime 对象、异常对象、SPLObjectStorage、数字、字符串、类型化数组、资源、DOM 节点。对象通过其自身的、非继承的、可枚举的属性进行比较。
参数
@param mixed $value 要比较的值。
@param mixed $other 要比较的另一个值。
返回
@return bool 如果值相等,则返回 true
,否则返回 false
。
示例
<?php use function _\isEqual; $object = [ 'a' => 1] $other = ['a' => '1'] isEqual($object, $other) // => true $object === $other // => false
isError
检查 value
是否为 \Exception
、\ParseError
、\Error、\Throwable
、\SoapFault、\DOMException
、\PDOException` 对象。
参数
@param mixed $value 要检查的值。
返回
@return boolean 如果 value
是错误对象,则返回 true
,否则返回 false
。
示例
<?php use function _\isError; isError(new \Exception()) // => true isError(\Exception::Class) // => false
数学
add
添加两个数字。
参数
@param (int | float | string) $augend 加法中的第一个数字。
@param (int | float | string) $addend 加法中的第二个数字。
返回
@return (int | float) 返回总和。
示例
<?php use function _\add; add(6, 4); // => 10
max
计算数组的最大值。如果数组为空或为假,则返回 null。
参数
@param (array | null) $array 要迭代的数组。
返回
@return (int | null) 返回最大值。
示例
<?php use function _\max; max([4, 2, 8, 6]); // => 8 max([]); // => null
maxBy
此方法类似于 max
,但它接受 iteratee
,该 iteratee
对数组中的每个元素进行调用以生成值排序的标准。iteratee 使用一个参数调用:(值)。
参数
@param array $array 要迭代的数组。
@param (callable | string) $iteratee 对每个元素调用的 iteratee。
返回
@return mixed 返回最大值。
示例
<?php use function _\maxBy; $objects = [['n' => 1], ['n' => 2]]; maxBy($objects, function($o) { return $o['n']; }); // => ['n' => 2] // The `property` iteratee shorthand. maxBy($objects, 'n'); // => ['n' => 2]
数字
clamp
将 number
限制在包含的 lower
和 upper
范围内。
参数
@param int $number 要限制的数字。
@param int $lower 下限。
@param int $upper 上限。
返回
@return int 返回限制后的数字。
示例
<?php use function _\clamp; clamp(-10, -5, 5) // => -5 clamp(10, -5, 5) // => 5
inRange
检查 number
是否在 start
和 end
之间。如果未指定 end
,则将其设置为 start
,然后 start
设置为 0
。如果 start
大于 end
,则交换参数以支持负范围。
参数
@param float $number 要检查的数字。
@param float $start 范围的开始。
@param float $end 范围的结束。
返回
@return boolean 如果 number
在范围内,则返回 true
,否则返回 false
。
示例
<?php use function _\inRange; inRange(3, 2, 4) // => true inRange(4, 8) // => true inRange(4, 2) // => false inRange(2, 2) // => false inRange(1.2, 2) // => true inRange(5.2, 4) // => false inRange(-3, -2, -6) // => true
random
产生一个介于包含的 lower
和 upper
范围内的随机数。如果只提供一个参数,则返回介于 0
和给定数字之间的数字。如果 floating
为 true
,或 lower
或 upper
为浮点数,则返回浮点数而不是整数。
参数
@param (int | float | bool) $lower 下限。
@param (int | float | bool) $upper 上限。
@param (bool | null) $floating 指定返回浮点数。
返回
@return (int | float) 返回随机数。
示例
<?php use function _\random; random(0, 5) // => an integer between 0 and 5 random(5) // => also an integer between 0 and 5 random(5, true) // => a floating-point number between 0 and 5 random(1.2, 5.2) // => a floating-point number between 1.2 and 5.2
对象
get
获取对象路径中的值。如果解析的值是 null,则返回 defaultValue。
参数
@param mixed $object 从中获取值的关联数组或对象。
@param (array | string) $path 点分隔或字符串数组。
@param mixed $defaultValue (可选)对于未解析或 null 值返回的值。
返回
@return mixed 返回解析的值。
示例
<?php use function _\get; $sampleArray = ["key1" => ["key2" => ["key3" => "val1", "key4" => ""]]]; get($sampleArray, 'key1.key2.key3'); // => "val1" get($sampleArray, 'key1.key2.key5', "default"); // => "default" get($sampleArray, 'key1.key2.key4', "default"); // => ""
pick
创建一个由选择的 object
属性组成的对象。
参数
@param object $object 源对象。
@param (string | string[]) $paths 要选择的属性路径。
返回
@return \stdClass 返回新的对象。
示例
<?php use function _\pick; $object = (object) ['a' => 1, 'b' => '2', 'c' => 3]; pick($object, ['a', 'c']); // => (object) ['a' => 1, 'c' => 3]
pickBy
创建一个由 object
属性组成的新对象,其中 predicate
对这些属性返回真值。断言函数以两个参数调用:(值,键)。
参数
@param (object | null) $object 源对象。
@param callable $predicate 对每个属性调用的函数。
返回
@return \stdClass 返回新的对象。
示例
<?php use function _\pickBy; $object = (object) ['a' => 1, 'b' => 'abc', 'c' => 3]; pickBy(object, 'is_numeric'); // => (object) ['a' => 1, 'c' => 3]
序列
chain
创建一个 lodash
包装实例,该实例将 value
包裹在显式方法链序列中。此类序列的结果必须通过 ->value()
解包。
参数
@param mixed $value 需要包装的值。
返回
@return _ 返回新的 lodash
包装实例。
示例
<?php use function _\chain; $users = [ ['user' => 'barney', 'age' => 36], ['user' => 'fred', 'age' => 40], ['user' => 'pebbles', 'age' => 1 ], ]; $youngest = chain($users) ->sortBy('age') ->map(function($o) { return $o['user'] . ' is ' . $o['age']; }) ->head() ->value(); // => 'pebbles is 1'
字符串
camelCase
将 string
转换为 camel case。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的 camel cased 字符串。
示例
<?php use function _\camelCase; camelCase('Foo Bar') // => 'fooBar' camelCase('--foo-bar--') // => 'fooBar' camelCase('__FOO_BAR__') // => 'fooBar'
capitalize
将 string
的第一个字符转换为大写,其余字符转换为小写。
参数
@param string $string 要转换为大写的字符串。
返回
@return string 返回转换后的字符串。
示例
<?php use function _\capitalize; capitalize('FRED') // => 'Fred'
deburr
通过将 [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) 和 [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) 字母转换为基本拉丁字母并删除 [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) 来去噪 string
。
参数
@param string $string 要去噪的字符串。
返回
@return string 返回去噪后的字符串。
示例
<?php use function _\deburr; deburr('déjà vu') // => 'deja vu'
endsWith
检查 string
是否以给定的目标字符串结尾。
参数
@param string $string 要检查的字符串。
@param string $target 要搜索的字符串。
@param int $position 搜索到的位置。
返回
@return boolean 如果 string
以 target
结尾,则返回 true
,否则返回 false
。
示例
<?php use function _\endsWith; endsWith('abc', 'c') // => true endsWith('abc', 'b') // => false endsWith('abc', 'b', 2) // => true
escape
将 string
中的 "&"、"<"、">"、'"' 和 '"' 字符转换为相应的 HTML 实体。
尽管 ">" 字符为了对称性而被转义,但像 ">" 和 "/" 这样的字符在 HTML 中不需要转义,除非它们是标签的一部分或未引用的属性值。有关更多详细信息,请参阅 Mathias Bynens 的文章(在 "semi-related fun fact" 下)。
当处理 HTML 时,您应该始终 引用属性值 以减少 XSS 向量。
参数
@param string $string 要转义的字符串。
返回
@return string 返回转义后的字符串。
示例
<?php use function _\escape; escape('fred, barney, & pebbles') // => 'fred, barney, & pebbles'
escapeRegExp
在 string
中转义 RegExp
特殊字符 "^"、" "$"、""、"."、"*"、"+"、"?"、"(")、")"、"["、"]"、"{"} 和 "|"。
参数
@param string $string 要转义的字符串。
返回
@return string 返回转义后的字符串。
示例
<?php use function _\escapeRegExp; escapeRegExp('[lodash](https://lodash.node.org.cn/)') // => '\[lodash\]\(https://lodash\.com/\)'
kebabCase
将 string
转换为 kebab case。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的 kebab cased 字符串。
示例
<?php use function _\kebabCase; kebabCase('Foo Bar') // => 'foo-bar' kebabCase('fooBar') // => 'foo-bar' kebabCase('__FOO_BAR__') // => 'foo-bar'
lowerCase
将 string
(作为空格分隔的单词)转换为小写。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的小写字符串。
示例
<?php use function _\lowerCase; lowerCase('--Foo-Bar--') // => 'foo bar' lowerCase('fooBar') // => 'foo bar' lowerCase('__FOO_BAR__') // => 'foo bar'
lowerFirst
将 string
的第一个字符转换为小写。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的字符串。
示例
<?php use function _\lowerFirst; lowerFirst('Fred') // => 'fred' lowerFirst('FRED') // => 'fRED'
pad
如果 string
的长度短于 length
,则在左右两侧填充 string
。如果填充字符不能被 length
均匀除尽,则截断填充字符。
参数
@param string $string 要填充的字符串。
@param int $length 填充长度。
@param string $chars 用作填充的字符串。
返回
@return string 返回填充后的字符串。
示例
<?php use function _\pad; pad('abc', 8) // => ' abc ' pad('abc', 8, '_-') // => '_-abc_-_' pad('abc', 2) // => 'abc'
padEnd
如果 string
的长度短于 length
,则在右侧填充 string
。如果填充字符超过 length
,则截断填充字符。
参数
@param string $string 要填充的字符串。
@param int $length 填充长度。
@param string $chars 用作填充的字符串。
返回
@return string 返回填充后的字符串。
示例
<?php use function _\padEnd; padEnd('abc', 6) // => 'abc ' padEnd('abc', 6, '_-') // => 'abc_-_' padEnd('abc', 2) // => 'abc'
padStart
如果 string
的长度短于 length
,则在左侧填充 string
。如果填充字符超过 length
,则截断填充字符。
s 参数:
@param string $string ='' 要填充的字符串。
@param int $length 填充长度。
@param string $chars 用作填充的字符串。
返回
@return string 返回填充后的字符串。
示例
<?php use function _\padStart; padStart('abc', 6) // => ' abc' padStart('abc', 6, '_-') // => '_-_abc' padStart('abc', 2) // => 'abc'
parseInt
将字符串转换为指定进制的整数。如果 radix
为 undefined
或 0
,则使用 10
作为进制,除非字符串是十六进制,在这种情况下,使用 16
作为进制。
注意: 此方法使用 PHP 内置的整数转换,这不一定与 ES5 的 parseInt
实现 相符。
参数
@param (int | float | string) $string 要转换的字符串。
@param int $radix 通过该进制来解释 string
。
返回
@return int 返回转换后的整数。
示例
<?php use function _\parseInt; parseInt('08') // => 8
repeat
重复给定的字符串 n
次。
参数
@param string $string 要重复的字符串。
@param int $n 重复字符串的次数。
返回
@return string 返回重复的字符串。
示例
<?php use function _\repeat; repeat('*', 3) // => '***' repeat('abc', 2) // => 'abcabc' repeat('abc', 0) // => ''
replace
在 string
中用 replacement
替换 pattern
的匹配项。
注意: 此方法基于 String#replace
。
参数
@param string $string 要修改的字符串。
@param string $pattern 要替换的模式。
@param (callable | string) $replacement 匹配替换。
返回
@return string 返回修改后的字符串。
示例
<?php use function _\replace; replace('Hi Fred', 'Fred', 'Barney') // => 'Hi Barney'
snakeCase
将字符串转换为 snake case。
参数
@param string $string 要转换的字符串。
返回
@return string 返回 snake case 格式的字符串。
示例
<?php use function _\snakeCase; snakeCase('Foo Bar') // => 'foo_bar' snakeCase('fooBar') // => 'foo_bar' snakeCase('--FOO-BAR--') // => 'foo_bar'
split
通过 separator
来分割 string
。
注意: 此方法基于 String#split
。
参数
@param string $string 要分割的字符串。
@param string $separator 分割的分隔符模式。
@param int $limit 结果的长度限制。
返回
@return array 返回字符串段。
示例
<?php use function _\split; split('a-b-c', '-', 2) // => ['a', 'b']
startCase
将字符串转换为 start case。
参数
@param string $string 要转换的字符串。
返回
@return string 返回 start case 格式的字符串。
示例
<?php use function _\startCase; startCase('--foo-bar--') // => 'Foo Bar' startCase('fooBar') // => 'Foo Bar' startCase('__FOO_BAR__') // => 'FOO BAR'
startsWith
检查字符串是否以给定的目标字符串开头。
参数
@param string $string 要检查的字符串。
@param string $target 要搜索的字符串。
@param int $position 从该位置开始搜索。
返回
@return boolean 如果字符串以 target
开头,则返回 true
,否则返回 false
。
示例
<?php use function _\startsWith; startsWith('abc', 'a') // => true startsWith('abc', 'b') // => false startsWith('abc', 'b', 1) // => true
template
创建一个编译后的模板函数,可以在 "interpolate" 分隔符中插入数据属性,在 "escape" 分隔符中转义插入的数据属性,并在 "evaluate" 分隔符中执行 PHP。数据属性可以作为模板中的自由变量访问。如果提供了设置对象,则它将优先于 $templateSettings
的值。
RegExp $options['escape'] = _::$templateSettings['escape'] HTML 的 "escape" 分隔符。RegExp $options['evaluate'] = _::$templateSettings['evaluate'] "evaluate" 分隔符。array $options['imports'] = _::$templateSettings['imports'] 要导入模板作为自由变量的对象。RegExp $options['interpolate'] = _::$templateSettings['interpolate'] "interpolate" 分隔符。
参数
@param string $string 模板字符串。
@param array $options 选项数组。
返回
@return callable 返回编译后的模板函数。
示例
<?php use function _\template; // Use the "interpolate" delimiter to create a compiled template. $compiled = template('hello <%= user %>!') $compiled([ 'user' => 'fred' ]) // => 'hello fred!' // Use the HTML "escape" delimiter to escape data property values. $compiled = template('<b><%- value %></b>') $compiled([ 'value' => '<script>' ]) // => '<b><script></b>' // Use the "evaluate" delimiter to execute JavaScript and generate HTML. $compiled = template('<% foreach($users as $user) { %><li><%- user %></li><% }%>') $compiled([ 'users' => ['fred', 'barney'] ]) // => '<li>fred</li><li>barney</li>' // Use the internal `print` function in "evaluate" delimiters. $compiled = template('<% print("hello " + $user)%>!') $compiled([ 'user' => 'barney' ]) // => 'hello barney!' // Use backslashes to treat delimiters as plain text. $compiled = template('<%= "\\<%- value %\\>" %>') $compiled([ 'value' => 'ignored' ]) // => '<%- value %>' // Use the `imports` option to import functions or classes with aliases. $text = '<% all($users, function($user) { %><li><%- user %></li><% })%>' $compiled = template($text, { 'imports': { '_\each': 'all' } }) $compiled([ 'users' => ['fred', 'barney'] ]) // => '<li>fred</li><li>barney</li>' // Use custom template delimiters. \_::$templateSettings['interpolate'] = '{{([\s\S]+?)}}' $compiled = template('hello {{ user }}!') $compiled([ 'user' => 'mustache' ]) // => 'hello mustache!' // Use the `source` property to access the compiled source of the template template($mainText)->source;
toLower
将字符串作为一个整体转换为小写。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的小写字符串。
示例
<?php use function _\toLower; toLower('--Foo-Bar--') // => '--foo-bar--' toLower('fooBar') // => 'foobar' toLower('__FOO_BAR__') // => '__foo_bar__'
toUpper
将字符串作为一个整体转换为大写。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的大写字符串。
示例
<?php use function _\toUpper; toUpper('--foo-bar--') // => '--FOO-BAR--' toUpper('fooBar') // => 'FOOBAR' toUpper('__foo_bar__') // => '__FOO_BAR__'
trim
从字符串 string
中删除前导和尾随空格或指定的字符。
参数
@param string $string 要修剪的字符串。
@param string $chars 要修剪的字符。
返回
@return string 返回修剪后的字符串。
示例
<?php use function _\trim; trim(' abc ') // => 'abc' trim('-_-abc-_-', '_-') // => 'abc'
trimEnd
从字符串 string
中删除尾随空格或指定的字符。
参数
@param string $string 要修剪的字符串。
@param string $chars 要修剪的字符。
返回
@return string 返回修剪后的字符串。
示例
<?php use function _\trimEnd; trimEnd(' abc ') // => ' abc' trimEnd('-_-abc-_-', '_-') // => '-_-abc'
trimStart
从字符串 string
中删除前导空格或指定的字符。
参数
@param string $string 要修剪的字符串。
@param string $chars 要修剪的字符。
返回
@return string 返回修剪后的字符串。
示例
<?php use function _\trimStart; trimStart(' abc ') // => 'abc ' trimStart('-_-abc-_-', '_-') // => 'abc-_-'
truncate
如果字符串长度超过给定的最大字符串长度,则截断字符串。截断字符串的最后字符将被省略字符串替换,默认为"..."。
length = 30 最大字符串长度。omission = '...' 表示文本被省略的字符串。separator 截断到分隔符的模式。
参数
@param string $string 要截断的字符串。
@param array $options 选项对象。
返回
@return string 返回截断后的字符串。
示例
<?php use function _\truncate; truncate('hi-diddly-ho there, neighborino') // => 'hi-diddly-ho there, neighbo...' truncate('hi-diddly-ho there, neighborino', [ 'length' => 24, 'separator' => ' ' ]) // => 'hi-diddly-ho there,...' truncate('hi-diddly-ho there, neighborino', [ 'length' => 24, 'separator' => '/,? +/' ]) // => 'hi-diddly-ho there...' truncate('hi-diddly-ho there, neighborino', [ 'omission' => ' [...]' ]) // => 'hi-diddly-ho there, neig [...]'
unescape
此方法为 escape
方法的逆操作,将 string
中的 HTML 实体 &
、<
、>
、"
和 '
转换为其对应的字符。
参数
@param string $string 要取消转义的字符串。
返回
@return string 返回取消转义的字符串。
示例
<?php use function _\unescape; unescape('fred, barney, & pebbles') // => 'fred, barney, & pebbles'
upperCase
将 string
(作为空格分隔的单词)转换为大写。
参数
@param string $string 要转换的字符串。
返回
@return string 返回大写字符串。
示例
<?php use function _\upperCase; upperCase('--foo-bar') // => 'FOO BAR' upperCase('fooBar') // => 'FOO BAR' upperCase('__foo_bar__') // => 'FOO BAR'
upperFirst
将 string
的第一个字符转换为大写。
参数
@param string $string 要转换的字符串。
返回
@return string 返回转换后的字符串。
示例
<?php use function _\upperFirst; upperFirst('fred') // => 'Fred' upperFirst('FRED') // => 'FRED'
words
将 string
分割成一个单词数组。
参数
@param string $string 要检查的字符串。
@param string $pattern 匹配单词的模式。
返回
@return array 返回 string
的单词。
示例
<?php use function _\words; words('fred, barney, & pebbles') // => ['fred', 'barney', 'pebbles'] words('fred, barney, & pebbles', '/[^, ]+/g') // => ['fred', 'barney', '&', 'pebbles']
工具
attempt
尝试调用 func
,返回结果或捕获的错误对象。任何额外的参数都会在调用 func
时提供。
s 参数:
@param callable $func 要尝试调用的函数。
@param array<int, mixed> $args 调用 func
时使用的参数。
返回
@return (mixed | \Throwable) 返回 func
的结果或错误对象。
示例
<?php use function _\attempt; // Avoid throwing errors for invalid PDO data source. $elements = attempt(function () { new \PDO(null); }); if (isError($elements)) { $elements = []; }
defaultTo
检查值以确定是否应该返回默认值。如果值是 NaN 或 null,则返回 defaultValue。
参数
@param mixed $value 任何值。
@param mixed $defaultValue 如果 $value 是 null 或 NAN,则返回的值。
返回
@return mixed 返回 value
。
示例
<?php use function _\defaultTo; $a = null; defaultTo($a, "default"); // => "default" $a = "x"; defaultTo($a, "default"); // => "x"
identity
此方法返回它接收的第一个参数。
参数
@param mixed $value 任何值。
返回
@return mixed 返回 value
。
示例
<?php use function _\identity; $object = ['a' => 1]; identity($object) === $object; // => true
property
创建一个函数,返回给定对象的 path
上的值。
参数
@param (array | string) $path 要获取的属性路径。
返回
@return callable 返回新的访问器函数。
示例
<?php use function _\property; $objects = [ [ 'a' => [ 'b' => 2 ] ], [ 'a' => [ 'b' => 1 ] ] ]; map($objects, property('a.b')); // => [2, 1] map(sortBy($objects, property(['a', 'b'])), 'a.b'); // => [1, 2]