类 ResultSet
修饰 Elastica ResultSet 以便使用正确的类来填充结果,并为返回的结果提供 Collection 接口。
属性摘要
-
$embeds protected
数组
嵌入类型引用
-
$entityClass protected
字符串
要包装结果的文档类的完整类名
-
$queryObject protected
Cake\ElasticSearch\Query
保存 Elasticsearch ORM 查询对象
-
$repoName protected
字符串
原始查询来自的类型的名称。
-
$resultSet protected
Elastica\ResultSet
保存结果集的原始实例
方法摘要
-
__construct() public
装饰器的构造函数
-
__debugInfo() public
调试输出挂钩方法。
-
__serialize() public
用于序列化 ResultSet 实例的魔术方法
-
__unserialize() public
用于反序列化 ResultSet 实例的魔术方法
-
_createMatcherFilter() protected
返回一个可调用对象,该对象接收一个值并返回它是否满足某个条件。
-
_extract() protected
从 $data 中返回一个列,可以通过迭代 $path 中包含的列名来提取。它将为用
{*}
表示的元素返回数组。 -
_propertyExtractor() protected
返回一个可调用对象,该对象可用于根据点分隔路径从数组或对象中提取属性或列。
-
_simpleExtract() protected
从 $data 中返回一个列,可以通过迭代 $path 中包含的列名来提取。
-
append() public
返回一个新的集合,作为将此集合中的元素列表与传入的元素列表连接的结果。
-
appendItem() public
追加一个单独的项目,创建一个新的集合。
-
avg() public
返回使用 $path 提取的所有值的平均值或此集合的平均值。
-
buffered() public
返回一个新的集合,其中包含此集合执行的操作。无论新的集合迭代多少次,这些操作都只执行一次。
-
cartesianProduct() public
创建一个新的集合,它是当前集合的笛卡尔积。
-
chunk() public
将集合分成给定大小的较小数组。
-
chunkWithKeys() public
将集合分成给定大小的较小数组。
-
combine() public
返回一个新的集合,其中包含基于值路径提取的值,然后按键路径索引。可选地,此方法可以根据组属性路径生成父组。
-
compile() public
迭代此集合中的所有元素一次,并执行它们的所有堆叠操作,最后返回一个包含结果的新集合。这对于将不可回绕的内部迭代器转换为可以回绕和多次使用的集合非常有用。
-
contains() public
如果 $value 存在于此集合中,则返回 true。比较既按值进行,也按类型进行。
-
count() public
返回当前集合的大小
-
countBy() public
将列表排序成组,并返回每个组中元素的数量。类似于 groupBy,但它不返回值列表,而是返回该组中值的计数。
-
countKeys() public
返回此迭代器中唯一键的数量。这与调用
toArray()
后集合将包含的元素数量相同。 -
countSuggests() public
返回当前建议的大小
-
current() public
返回迭代的当前文档
-
each() public
将回调应用于此集合中的元素。
-
every() public
如果此集合中的所有值都通过回调提供的真值测试,则返回 true。
-
extract() public
返回一个新的集合,其中包含在每个元素中找到的列或属性值。
-
filter() public
遍历集合中的每个值,并返回另一个包含所有通过真值测试的值的集合。只有回调返回 true 的值才会出现在结果集合中。
-
first() public
返回此集合中的第一个结果
-
firstMatch() public
返回第一个与条件中列出的所有键值对匹配的结果。
-
getAggregation() public
从此结果集中检索特定的聚合
-
getAggregations() public
返回所有聚合结果
-
getMaxScore() public
返回找到的结果的最大分数
-
getQuery() public
返回原始的 \Elastica\Query 实例
-
getResponse() public
返回响应对象
-
getResults() public
返回所有结果
-
getSuggests() public
返回所有建议
-
getTotalHits() public
返回找到的命中总数
-
getTotalTime() public
返回此搜索完成的总毫秒数
-
groupBy() public
将集合分成集合,根据将每个值通过回调运行的结果进行分组。如果 $callback 是一个字符串而不是一个可调用对象,则根据每个值的 $callback 命名的属性进行分组。
-
hasSuggests() public
如果响应包含建议结果,则返回 true;否则返回 false。
-
hasTimedOut() public
如果查询超时,则返回 true。
-
indexBy() public
给定一个列表和一个返回列表中每个元素的键(或属性名称)的回调函数,返回一个包含每个项目的索引的对象。就像 groupBy 一样,但用于你知道你的键是唯一的。
-
insert() public
返回一个新的集合,其中包含在
$values
中找到的每个元素作为此集合中对应元素的属性。将插入值的属性由$path
参数描述。 -
isEmpty() public
返回此集合中是否有元素
-
jsonSerialize() public
返回可以转换为 JSON 的数据。这与
toArray()
返回相同的数据,其中只包含唯一的键。 -
last() public
返回此集合中的最后一个结果
-
lazy() public
返回一个新的集合,其中保证在它之后链接的任何操作都将懒惰地执行。也就是说,元素将一次产生一个。
-
listNested() public
返回一个新的集合,其中包含此集合中的每个元素,在展平树结构之后。树结构是通过将元素嵌套在一个具有已知名称的键下定义的。可以通过使用 '$nestingKey' 参数来指定此名称。
-
map() public
使用提供的可调用对象修改此集合中的每个值后,返回另一个集合。
-
match() public
遍历列表中的每个值,返回一个包含所有包含 $conditions 中列出的所有键值对的值的 Collection。
-
max() public
根据属性排序后,返回此集合中的顶部元素。有关回调和 $sort 参数的信息,请查看 sortBy 方法
-
median() public
返回使用 $path 提取的所有值的中间值或此集合的中间值。
-
min() public
根据属性排序后,返回此集合中的底部元素。有关回调和 $sort 参数的信息,请查看 sortBy 方法
-
nest() public
返回一个新的集合,其中值根据 id 属性路径和父 id 属性路径嵌套在树状结构中。
-
newCollection() protected
返回一个新的集合。
-
optimizeUnwrap() 受保护
解包此迭代器并返回最简单的可遍历对象,可用于获取数据
-
prepend() 公共
在集合前面添加一组项目,以创建一个新的集合
-
prependItem() 公共
在集合前面添加单个项目,以创建一个新的集合。
-
reduce() 公共
将此集合中的值折叠为单个值,作为将回调函数应用于所有元素的结果。$zero 是缩减的初始状态,其每个后续步骤应由回调函数返回。如果省略 $zero,则将使用集合的第一个值代替,并且缩减将从第二个项目开始。
-
reject() 公共
查看集合中的每个值,并返回另一个集合,其中包含所有未通过真实测试的值。这是
filter
的反面。 -
sample() 公共
从此集合中返回一个包含最多 $length 个随机元素的新集合
-
serialize() 公共
返回此对象的字符串表示形式,可用于重建它
-
shuffle() 公共
返回一个包含按随机顺序排列的元素的新集合,此函数不保留集合中的原始键。
-
skip() 公共
返回一个新的集合,该集合将跳过迭代开始时指定的元素数量。
-
some() 公共
如果此集合中的任何值通过回调中提供的真实测试,则返回 true。
-
sortBy() 公共
从此集合中的元素返回一个排序的迭代器,根据将回调函数应用于每个值的結果进行排名。参数 $path 也可以是表示列或属性名称的字符串。
-
stopWhen() 公共
创建一个新的集合,当迭代时,如果提供的条件评估为 true,则将停止生成结果。
-
sumOf() 公共
返回使用 $matcher 或此集合提取的所有值的总和。
-
take() 公共
返回一个包含此集合创建的内部顺序中的最多 $length 个元素的新集合。如果传递了第二个参数,它将确定从哪个位置开始获取元素。
-
takeLast() 公共
返回集合的最后 N 个元素
-
through() 公共
将此集合作为其第一个参数传递给可调用对象。这对于使用另一个对象装饰整个集合很有用。
-
toArray() 公共
返回结果的数组表示形式
-
toList() 公共
返回结果的按数字索引的数组表示形式。这等效于调用
toArray(false)
-
transpose() 公共
将行和列转置为列和行
-
unfold() 公共
创建一个新的集合,其中项目是由应用于原始集合中每个项目的转换器函数生成的项目列表的串联。
-
unique() 公共
循环遍历集合中的每个值,并返回一个新的集合,其中只包含根据
callback
返回的值唯一的值。 -
unserialize() 公共
反序列化传递的字符串并重建 ResultSet 实例
-
unwrap() 公共
返回最接近的嵌套迭代器,可以安全地遍历它而不会丢失任何可能的转换。这主要用于删除仅能减慢迭代过程的空 IteratorIterator 包装器。
-
zip() 公共
使用位置索引作为参考,将此集合中的元素与传递的可迭代对象的每个元素结合起来。
-
zipWith() 公共
使用位置索引作为参考,将此集合中的元素与传递的可迭代对象的每个元素结合起来。
方法详情
__construct() ¶ 公共
__construct(Elastica\ResultSet $resultSet, Cake\ElasticSearch\Query $query)
装饰器的构造函数
参数
-
Elastica\ResultSet
$resultSet 要包装的 Elastica 结果
-
Cake\ElasticSearch\Query
$query Elasticsearch 查询对象
__unserialize() ¶ 公共
__unserialize(array $data): void
用于反序列化 ResultSet 实例的魔术方法
参数
-
array
$data 序列化后的数据
返回
void
_createMatcherFilter() ¶ 受保护
_createMatcherFilter(array $conditions): Closure
返回一个可调用对象,该对象接收一个值并返回它是否满足某个条件。
参数
-
array
$conditions 要匹配的条件的键值列表,其中键是要从当前项目中获取的属性路径,而值是要与项目进行比较的值。
返回
Closure
_extract() ¶ 受保护
_extract(ArrayAccess<string|int, mixed>|array $data, list<string> $parts): mixed
从 $data 中返回一个列,可以通过迭代 $path 中包含的列名来提取。它将为用 {*}
表示的元素返回数组。
参数
-
ArrayAccess<string|int, mixed>|array
$data 数据。
-
list<string>
$parts 要从中提取的路径。
返回
mixed
_propertyExtractor() ¶ 受保护
_propertyExtractor(callable|string $path): Closure
返回一个可调用对象,该对象可用于根据点分隔路径从数组或对象中提取属性或列。
参数
-
callable|string
$path 要跟随的列的点分隔路径,以便可以返回路径中的最后一个元素,或者一个可调用对象来完成此操作。
返回
Closure
_simpleExtract() ¶ 受保护
_simpleExtract(ArrayAccess<string|int, mixed>|array $data, list<string> $parts): mixed
从 $data 中返回一个列,可以通过迭代 $path 中包含的列名来提取。
参数
-
ArrayAccess<string|int, mixed>|array
$data 数据。
-
list<string>
$parts 要从中提取的路径。
返回
mixed
append() ¶ 公共
append(iterable $items): self
返回一个新的集合,作为将此集合中的元素列表与传入的元素列表连接的结果。
参数
-
iterable
$items
返回
self
appendItem() ¶ 公共
appendItem(mixed $item, mixed $key = null): self
追加一个单独的项目,创建一个新的集合。
参数
-
mixed
$item -
mixed
$key 可选
返回
self
avg() ¶ 公共
avg(callable|string|null $path = null): float|int|null
返回使用 $path 提取的所有值的平均值或此集合的平均值。
示例
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
空集或 0 行的平均值为 null
。包含 null
值的集合不被视为空。
参数
-
callable|string|null
$path 可选
返回
float|int|null
buffered() ¶ 公共
buffered(): self
返回一个新的集合,其中包含此集合执行的操作。无论新的集合迭代多少次,这些操作都只执行一次。
这也可用于使任何不可回绕的迭代器可回绕。
返回
self
cartesianProduct() ¶ 公共
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
创建一个新的集合,它是当前集合的笛卡尔积。
为了创建笛卡尔积,集合必须包含单个维度的数据。
示例
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
参数
-
callable|null
$operation 可选 允许您自定义产品结果的可调用对象。
-
callable|null
$filter 可选 一个过滤回调,它必须返回 true 才能使结果成为最终结果的一部分。
返回
Cake\Collection\CollectionInterface
抛出
LogicException
chunk() ¶ 公共
chunk(int $chunkSize): self
将集合分成给定大小的较小数组。
示例
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
参数
-
int
$chunkSize
返回
self
chunkWithKeys() ¶ 公共
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
将集合分成给定大小的较小数组。
示例
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
参数
-
int
$chunkSize -
bool
$keepKeys 可选
返回
self
combine() ¶ 公共
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
返回一个新的集合,其中包含基于值路径提取的值,然后按键路径索引。可选地,此方法可以根据组属性路径生成父组。
示例
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar'],
];
参数
-
callable|string
$keyPath -
callable|string
$valuePath -
callable|string|null
$groupPath 可选
返回
self
compile() ¶ 公共
compile(bool $keepKeys = true): self
迭代此集合中的所有元素一次,并执行它们的所有堆叠操作,最后返回一个包含结果的新集合。这对于将不可回绕的内部迭代器转换为可以回绕和多次使用的集合非常有用。
一个常见的用例是重复使用同一个变量来计算不同的数据。在这些情况下,首先编译集合,然后对其应用更多操作可能会有帮助,并且效率更高。
示例
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
在上面的例子中,如果在编译集合之前没有编译,map
、sortBy
和 extract
的迭代将执行两次:一次用于获取 $isJohnHere
,另一次用于获取 $allButJohn
您可以将此方法视为在集合中创建复杂计算的保存点的一种方法。
参数
-
bool
$keepKeys 可选
返回
self
contains() ¶ 公共
contains(mixed $value): bool
如果 $value 存在于此集合中,则返回 true。比较既按值进行,也按类型进行。
参数
-
mixed
$value
返回
bool
count() ¶ 公共
count(): int
返回当前集合的大小
警告
将更改迭代器的当前位置
在迭代这些集合的同时调用此方法(例如在 foreach 中),会导致未定义的行为。避免这样做。
消耗所有 NoRewindIterator 集合的元素
在某些类型的集合上,调用此方法可能会使其在之后无法使用。也就是说,您可能无法从中获取元素,也无法再对其进行迭代。
具体来说,任何包装生成器(带有 yield 语句的函数)或未缓冲的数据库游标的集合,在调用其上的 count()
后,将不再接受任何其他函数调用。
使用 buffered()
方法创建新的集合以解决此问题。
可以报告比唯一键更多的元素
通过将集合追加在一起或通过使内部迭代器返回重复键而构造的任何集合,使用此函数报告的元素数量将比将集合转换为带键的数组后最终的元素数量更大。这是因为重复的键将在最终数组中折叠为单个键,而此计数方法只关心将其转换为普通列表后元素的数量。
如果您需要在考虑键后元素的数量(唯一键的数量),您可以调用 countKeys()
返回
int
countBy() ¶ 公共
countBy(callable|string $path): self
将列表排序成组,并返回每个组中元素的数量。类似于 groupBy,但它不返回值列表,而是返回该组中值的计数。
当 $callback 是一个字符串时,它应该是要提取的属性名称,或者是要跟随以获取路径中最后一个元素的属性的点分隔路径。
示例
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
参数
-
callable|string
$path
返回
self
countKeys() ¶ 公共
countKeys(): int
返回此迭代器中唯一键的数量。这与调用 toArray()
后集合将包含的元素数量相同。
此方法带有一些注意事项。有关详细信息,请参阅 CollectionInterface::count()
。
返回
int
each() ¶ public
each(callable $callback): $this
将回调应用于此集合中的元素。
示例
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
参数
-
callable
$callback
返回
$this
every() ¶ public
every(callable $callback): bool
如果此集合中的所有值都通过回调提供的真值测试,则返回 true。
回调函数接收被测试元素的值和键,如果测试通过则应返回 true。
示例
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
空集合始终返回 true。
参数
-
callable
$callback
返回
bool
extract() ¶ public
extract(callable|string $path): self
返回一个新的集合,其中包含在每个元素中找到的列或属性值。
匹配器可以是一个包含属性名的字符串,也可以是一个以点分隔的属性路径,用于获取路径中的最后一个属性。
如果在集合中的特定元素中找不到列或属性,则该位置将用 null 填充。
示例
提取数组中所有评论的用户名
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
也可以从嵌套属性中提取扁平化的集合
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
参数
-
callable|string
$path
返回
self
filter() ¶ public
filter(callable|null $callback = null): self
遍历集合中的每个值,并返回另一个包含所有通过真值测试的值的集合。只有回调返回 true 的值才会出现在结果集合中。
每次执行回调函数时,它都会按顺序接收当前迭代中元素的值、元素的键以及此集合作为参数。
示例
在一个数组中过滤奇数,最后结果集合中将只存在值 2
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
参数
-
callable|null
$callback 可选
返回
self
firstMatch() ¶ public
firstMatch(array $conditions): mixed
返回第一个与条件中列出的所有键值对匹配的结果。
参数
-
array
$conditions
返回
mixed
getAggregation() ¶ public
getAggregation(string $name): array
从此结果集中检索特定的聚合
参数
-
string
$name 所需聚合的名称
返回
数组
抛出
Elastica\Exception\InvalidException
如果找不到给定名称的聚合
groupBy() ¶ public
groupBy(callable|string $path, bool $preserveKeys = false): Cake\Collection\CollectionInterface
将集合分成集合,根据将每个值通过回调运行的结果进行分组。如果 $callback 是一个字符串而不是一个可调用对象,则根据每个值的 $callback 命名的属性进行分组。
当 $callback 是一个字符串时,它应该是要提取的属性名称,或者是要跟随以获取路径中最后一个元素的属性的点分隔路径。
示例
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
参数
-
callable|string
$path 用于分组的列名或返回值的回调函数。 或一个函数,从提供的元素中返回分组键
-
bool
$preserveKeys 可选 是否在对值进行分组时保留现有集合的键。默认为 false。
返回
Cake\Collection\CollectionInterface
indexBy() ¶ public
indexBy(callable|string $path): self
给定一个列表和一个返回列表中每个元素的键(或属性名称)的回调函数,返回一个包含每个项目的索引的对象。就像 groupBy 一样,但用于你知道你的键是唯一的。
当 $callback 是一个字符串时,它应该是要提取的属性名称,或者是要跟随以获取路径中最后一个元素的属性的点分隔路径。
示例
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
参数
-
callable|string
$path
返回
self
insert() ¶ public
insert(string $path, mixed $values): self
返回一个新的集合,其中包含在 $values
中找到的每个元素作为此集合中对应元素的属性。将插入值的属性由 $path
参数描述。
$path 可以是一个包含属性名的字符串,也可以是一个以点分隔的属性路径,用于获取路径中的最后一个属性。
如果在集合中的特定元素中找不到列或属性,则该元素将保持不变。
示例
将年龄插入到包含用户的集合中
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
参数
-
string
$path -
mixed
$values
返回
self
isEmpty() ¶ public
isEmpty(): bool
返回此集合中是否有元素
示例
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
(new Collection([]))->isEmpty(); // true
返回
bool
jsonSerialize() ¶ public
jsonSerialize(): array
返回可以转换为 JSON 的数据。这与 toArray()
返回相同的数据,其中只包含唯一的键。
JsonSerializable 接口的一部分。
返回
数组
lazy() ¶ public
lazy(): self
返回一个新的集合,其中保证在它之后链接的任何操作都将懒惰地执行。也就是说,元素将一次产生一个。
惰性集合只能迭代一次。第二次尝试会导致错误。
返回
self
listNested() ¶ public
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
返回一个新的集合,其中包含此集合中的每个元素,在展平树结构之后。树结构是通过将元素嵌套在一个具有已知名称的键下定义的。可以通过使用 '$nestingKey' 参数来指定此名称。
默认情况下,将返回树中遵循深度优先搜索的所有元素,即从每个分支的顶部父节点到叶子节点的元素。
可以通过在 '$dir' 参数中传递 'asc' 来返回从底部到顶部的所有元素,使用广度优先搜索方法。也就是说,它将首先返回相同树深度的所有元素,然后从底部到顶部。
最后,您可以指定只获取树结构中的叶节点集合。通过在第一个参数中传递 'leaves' 来实现。
第一个参数的可能值是以下常量的别名,可以使用它们而不是别名
- desc: RecursiveIteratorIterator::SELF_FIRST
- asc: RecursiveIteratorIterator::CHILD_FIRST
- leaves: RecursiveIteratorIterator::LEAVES_ONLY
示例
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
参数
-
string|int
$order 可选 -
callable|string
$nestingKey 可选
返回
self
map() ¶ public
map(callable $callback): self
使用提供的可调用对象修改此集合中的每个值后,返回另一个集合。
每次执行回调函数时,它都会按顺序接收当前迭代中元素的值、元素的键以及此集合作为参数。
示例
获取一个布尔值集合,其中 true 表示一个人是女性
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
参数
-
callable
$callback
返回
self
match() ¶ public
match(array $conditions): self
遍历列表中的每个值,返回一个包含所有包含 $conditions 中列出的所有键值对的值的 Collection。
示例
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']],
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]]
]
参数
-
array
$conditions
返回
self
max() ¶ public
max(callable|string $path, int $sort = SORT_NUMERIC): mixed
根据属性排序后,返回此集合中的顶部元素。有关回调和 $sort 参数的信息,请查看 sortBy 方法
示例
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
参数
-
callable|string
$path -
int
$sort 可选
返回
mixed
median() ¶ public
median(callable|string|null $path = null): float|int|null
返回使用 $path 提取的所有值的中间值或此集合的中间值。
示例
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
空集或 0 行的中位数为 null
。包含 null
值的集合不被视为空。
参数
-
callable|string|null
$path 可选
返回
float|int|null
min() ¶ public
min(callable|string $path, int $sort = SORT_NUMERIC): mixed
根据属性排序后,返回此集合中的底部元素。有关回调和 $sort 参数的信息,请查看 sortBy 方法
示例
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
参数
-
callable|string
$path -
int
$sort 可选
返回
mixed
nest() ¶ public
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
返回一个新的集合,其中值根据 id 属性路径和父 id 属性路径嵌套在树状结构中。
参数
-
callable|string
$idPath -
callable|string
$parentPath -
string
$nestingKey 可选
返回
self
newCollection() ¶ protected
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
返回一个新的集合。
允许使用此特性的类确定它们自己的返回集合接口类型
参数
-
mixed
...$args 构造函数参数。
返回
Cake\Collection\CollectionInterface
optimizeUnwrap() ¶ protected
optimizeUnwrap(): Iterator|array
解包此迭代器并返回最简单的可遍历对象,可用于获取数据
返回
Iterator|array
prependItem() ¶ public
prependItem(mixed $item, mixed $key = null): self
在集合前面添加单个项目,以创建一个新的集合。
参数
-
mixed
$item -
mixed
$key 可选
返回
self
reduce() ¶ public
reduce(callable $callback, mixed $initial = null): mixed
将此集合中的值折叠为单个值,作为将回调函数应用于所有元素的结果。$zero 是缩减的初始状态,其每个后续步骤应由回调函数返回。如果省略 $zero,则将使用集合的第一个值代替,并且缩减将从第二个项目开始。
参数
-
callable
$callback -
mixed
$initial 可选
返回
mixed
reject() ¶ public
reject(callable $callback = null): self
查看集合中的每个值,并返回另一个集合,其中包含所有未通过真实测试的值。这是 filter
的反面。
每次执行回调函数时,它都会按顺序接收当前迭代中元素的值、元素的键以及此集合作为参数。
示例
在一个数组中过滤偶数,最后结果集合中将只存在值 1 和 3
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
参数
-
callable
$callback 可选
返回
self
sample() ¶ public
sample(int $length = 10): self
从此集合中返回一个包含最多 $length 个随机元素的新集合
参数
-
int
$length 可选
返回
self
some() ¶ public
some(callable $callback): bool
如果此集合中的任何值通过回调中提供的真实测试,则返回 true。
回调函数接收被测试元素的值和键,如果测试通过则应返回 true。
示例
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
参数
-
callable
$callback
返回
bool
sortBy() ¶ public
sortBy(callable|string $path, int $order = SORT_DESC, int $sort = SORT_NUMERIC): self
从此集合中的元素返回一个排序的迭代器,根据将回调函数应用于每个值的結果进行排名。参数 $path 也可以是表示列或属性名称的字符串。
回调函数将接收 $items 中每个元素作为第一个参数,回调函数返回的值将用作对该元素进行排序的值。请注意,回调函数可能会针对每个元素被调用多次。
示例
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
参数
-
callable|string
$path -
int
$order 可选 -
int
$sort 可选
返回
self
stopWhen() ¶ public
stopWhen(callable|array $condition): self
创建一个新的集合,当迭代时,如果提供的条件评估为 true,则将停止生成结果。
这对于处理无限迭代器或在特定点开始返回无效元素的任何生成器很有用。例如,当从文件流中读取行时,您可能希望在达到特定值后停止迭代。
示例
获取 CSV 文件中的行数组,直到时间戳列小于日期
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
获取元素,直到找到第一个未批准的消息
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
参数
-
callable|array
$condition
返回
self
sumOf() ¶ public
sumOf(callable|string|null $path = null): float|int
返回使用 $matcher 或此集合提取的所有值的总和。
示例
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]],
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
参数
-
callable|string|null
$path 可选
返回
float|int
take() ¶ public
take(int $length = 1, int $offset = 0): self
返回一个包含此集合创建的内部顺序中的最多 $length 个元素的新集合。如果传递了第二个参数,它将确定从哪个位置开始获取元素。
参数
-
int
$length 可选 -
int
$offset 可选
返回
self
takeLast() ¶ public
takeLast(int $length): self
返回集合的最后 N 个元素
示例
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
参数
-
int
$length
返回
self
through() ¶ public
through(callable $callback): self
将此集合作为其第一个参数传递给可调用对象。这对于使用另一个对象装饰整个集合很有用。
示例
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
参数
-
callable
$callback
返回
self
transpose() ¶ public
transpose(): Cake\Collection\CollectionInterface
将行和列转置为列和行
示例
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
返回
Cake\Collection\CollectionInterface
抛出
LogicException
unfold() ¶ public
unfold(callable|null $callback = null): self
创建一个新的集合,其中项目是由应用于原始集合中每个项目的转换器函数生成的项目列表的串联。
转换函数将按顺序接收集合中每个项目的 value 和 key,它必须返回一个数组或一个可遍历的对象,可以将其连接到最终结果。
如果没有传递转换器函数,则将使用“身份”函数。这在源集合中的每个元素都是要一个接一个追加的项目列表时很有用。
示例
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
使用转换器
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
参数
-
callable|null
$callback 可选
返回
self
unique() ¶ public
unique(callable $callback = null): self
循环遍历集合中的每个值,并返回一个新的集合,其中只包含根据 callback
返回的值唯一的值。
回调将值作为第一个参数传递,并将键作为第二个参数传递。
参数
-
callable
$callback 可选
返回
self
unserialize() ¶ public
unserialize(string $serialized): void
反序列化传递的字符串并重建 ResultSet 实例
参数
-
string
$serialized 序列化后的 ResultSet 信息
返回
void
unwrap() ¶ public
unwrap(): Iterator
返回最接近的嵌套迭代器,可以安全地遍历它而不会丢失任何可能的转换。这主要用于删除仅能减慢迭代过程的空 IteratorIterator 包装器。
返回
Iterator
zip() ¶ public
zip(iterable ...$items): self
使用位置索引作为参考,将此集合中的元素与传递的可迭代对象的每个元素结合起来。
示例
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
参数
-
iterable
...$items
返回
self
zipWith() ¶ public
zipWith(iterable $items, callable $callback): self
使用位置索引作为参考,将此集合中的元素与传递的可迭代对象的每个元素结合起来。
结果元素将是 $callable 函数的返回值。
示例
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
参数
-
iterable
$items -
callable
$callback
返回
self