CakePHP
  • 文档
    • 书籍
    • API
    • 视频
    • 报告安全问题
    • 隐私政策
    • 标识和商标
  • 商业解决方案
  • 周边产品
  • 公路旅行
  • 团队
  • 社区
    • 社区
    • 参与
    • 问题 (Github)
    • 烘焙坊
    • 精选资源
    • 培训
    • 聚会
    • 我的 CakePHP
    • CakeFest
    • 新闻通讯
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • 帮助和支持
    • 论坛
    • Stack Overflow
    • IRC
    • Slack
    • 付费支持
CakePHP

C CakePHP 5.1 Chiffon API

  • 项目
    • CakePHP
      • CakePHP
      • Chronos
      • Elastic Search
      • 队列
  • 版本
    • 5.1
      • 5.1
      • 5.0
      • 4.5
      • 4.4
      • 4.3
      • 4.2
      • 4.1
      • 4.0
      • 3.10
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

命名空间

  • 全局
  • Cake
    • Cache
    • Collection
      • Iterator
    • Command
    • Console
    • Controller
    • Core
    • Database
    • Datasource
    • Error
    • Event
    • Form
    • Http
    • I18n
    • Log
    • Mailer
    • Network
    • ORM
    • Routing
    • TestSuite
    • Utility
    • Validation
    • View

类 ZipIterator

创建一个迭代器,它返回成对分组的元素

示例

 $iterator = new ZipIterator([[1, 2], [3, 4]]);
 $iterator->toList(); // Returns [[1, 3], [2, 4]]

您还可以选择一个自定义函数来将元素压缩在一起,例如按索引进行求和

示例

 $iterator = new ZipIterator([[1, 2], [3, 4]], function ($a, $b) {
   return $a + $b;
 });
 $iterator->toList(); // Returns [4, 6]
命名空间: Cake\Collection\Iterator

属性摘要

  • $_callback protected
    callable|null

    用于将项目压缩在一起的函数

  • $_iterators protected
    array

    包含已附加的原始迭代器对象

  • $multipleIterator protected
    MultipleIterator

方法摘要

  • __construct() public

    创建迭代器以通过所有传递的迭代器的对应索引合并所有迭代器的值。

  • __serialize() public

    用于序列化迭代器实例的魔术方法。

  • __unserialize() public

    用于重建迭代器实例的魔术方法。

  • _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() 后集合中包含的元素数量相同

  • current() public

    返回将所有迭代器的所有元素压缩在一起的结果值,这些元素具有相同的 positional index。

  • each() public

    将回调应用于此集合中的元素。

  • every() public

    如果此集合中的所有值都通过回调中提供的真值测试,则返回 true。

  • extract() public

    返回一个包含每个元素中找到的列或属性值的新集合。

  • filter() public

    查看集合中的每个值,并返回另一个集合,其中包含通过真值测试的所有值。只有回调返回 true 的值才会出现在结果集合中。

  • first() public

    返回此集合中的第一个结果

  • firstMatch() public

    返回第一个与条件中列出的所有键值对匹配的结果。

  • groupBy() public

    将集合拆分为集合,根据对每个值运行回调的结果进行分组。如果 $callback 是一个字符串而不是一个可调用对象,则根据每个值上由 $callback 命名的属性进行分组。

  • indexBy() public

    给定一个列表和一个回调函数,该函数为列表中的每个元素返回一个键(或属性名称),返回一个具有每个项目索引的对象。就像 groupBy 一样,但对于知道键是唯一的那些情况。

  • insert() public

    返回一个新集合,其中包含 $values 中找到的每个元素作为此集合中对应元素的属性。将插入值的属性由 $path 参数描述。

  • isEmpty() public

    返回此集合中是否有元素

  • jsonSerialize() public

    返回可以转换为 JSON 的数据。它返回与 toArray() 相同的数据,该数据仅包含唯一键。

  • key() public

    实现 Iterator::key()。

  • 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

    返回一个新的集合。

  • next() public

    实现 Iterator::next()。

  • optimizeUnwrap() protected

    解开此迭代器并返回最简单的可遍历对象,该对象可用于提取数据

  • prepend() public

    将一组项目预先添加到集合中以创建新集合

  • prependItem() public

    预先添加单个项目以创建新集合。

  • reduce() public

    将此集合中的值折叠成单个值,作为将回调函数应用于所有元素的结果。$initial 是减少的初始状态,并且回调函数应返回它的每个后续步骤。如果省略 $initial,则将使用集合的第一个值代替它,并且减少将从第二个项目开始。

  • reject() public

    查看集合中的每个值,并返回另一个集合,其中包含所有未通过真值测试的值。这与 filter 相反。

  • rewind() public

    实现 Iterator::rewind()。

  • sample() public

    返回一个新集合,其中包含从当前集合中随机选择的 $length 个元素。

  • shuffle() public

    返回一个新集合,其中元素按随机顺序排列,此函数不会保留集合中的原始键。

  • skip() public

    返回一个新集合,它将跳过迭代开始处的指定数量的元素。

  • some() public

    如果当前集合中的任何值通过回调提供的真值测试,则返回 true。

  • sortBy() public

    从当前集合中的元素中返回一个排序的迭代器,根据将回调函数应用于每个值的结果进行排名。$path 参数也可以是一个字符串,表示列或属性名称。

  • stopWhen() public

    创建一个新的集合,当迭代时,如果提供的条件计算结果为 true,则将停止产生结果。

  • sumOf() public

    返回使用 $matcher 提取的所有值或当前集合的总和。

  • take() public

    返回一个新集合,其中包含当前集合创建的内部顺序中的最大 $length 个元素。如果传递了第二个参数,它将确定从哪个位置开始获取元素。

  • takeLast() public

    返回集合的最后 N 个元素。

  • through() public

    将当前集合作为其第一个参数传递给一个可调用对象。这对于使用另一个对象装饰整个集合很有用。

  • toArray() public

    返回结果的数组表示。

  • toList() public

    返回结果的按数字索引的数组表示。这等同于调用 toArray(false)。

  • transpose() public

    将行和列转置为列和行。

  • unfold() public

    创建一个新集合,其中项目是通过将转换器函数应用于原始集合中的每个项目生成的项目列表的串联。

  • unique() public

    遍历集合中的每个值,并返回一个新集合,其中只包含根据 callback 返回的值而确定的唯一值。

  • unwrap() public

    返回可以安全遍历而不会丢失任何可能的转换的最接近的嵌套迭代器。这主要用于删除只能减慢迭代过程的空 IteratorIterator 包装器。

  • valid() public

    实现 Iterator::valid()。

  • zip() public

    将当前集合的元素与传递的迭代器的每个元素组合,使用它们的位序索引作为参考。

  • zipWith() public

    将当前集合的元素与传递的迭代器的每个元素组合,使用它们的位序索引作为参考。

方法详情

__construct() ¶ public

__construct(array $sets, callable|null $callable = null)

创建迭代器以通过所有传递的迭代器的对应索引合并所有迭代器的值。

参数
array $sets

要压缩的数组或迭代器的列表。

callable|null $callable optional

用于压缩每个迭代器的元素的函数。

__serialize() ¶ public

__serialize(): array

用于序列化迭代器实例的魔术方法。

返回
array

__unserialize() ¶ public

__unserialize(array $data): void

用于重建迭代器实例的魔术方法。

参数
array $data

数据数组。

返回
void

_createMatcherFilter() ¶ protected

_createMatcherFilter(array $conditions): Closure

返回一个可调用对象,它接收一个值,并将返回该值是否满足特定条件。

参数
array $conditions

要匹配的条件的键值列表,其中键是当前项目中要获取的属性路径,值是要与项目进行比较的值。

返回
Closure

_extract() ¶ protected

_extract(ArrayAccess<string|int, mixed>|array $data, list<string> $parts): mixed

从 $data 中返回一个列,该列可以通过遍历 $path 中包含的列名来提取。它将返回用 {*} 表示的元素的数组

参数
ArrayAccess<string|int, mixed>|array $data

数据。

list<string> $parts

要从中提取的路径。

返回
mixed

_propertyExtractor() ¶ protected

_propertyExtractor(callable|string $path): Closure

返回一个可调用对象,该对象可用于根据点分隔路径从数组或对象中提取属性或列。

参数
callable|string $path

要遵循的列的点分隔路径,以便可以返回最后的路径,或者是一个可调用对象,它将负责执行此操作。

返回
Closure

_simpleExtract() ¶ protected

_simpleExtract(ArrayAccess<string|int, mixed>|array $data, list<string> $parts): mixed

从 $data 中返回一个列,该列可以通过遍历 $path 中包含的列名来提取

参数
ArrayAccess<string|int, mixed>|array $data

数据。

list<string> $parts

要从中提取的路径。

返回
mixed

append() ¶ public

append(iterable $items): self

返回一个新集合,它是将此集合中的元素列表与传递的元素列表连接起来的结果

参数
iterable $items
返回
self

appendItem() ¶ public

appendItem(mixed $item, mixed $key = null): self

附加单个项目以创建新集合。

参数
mixed $item
mixed $key optional
返回
self

avg() ¶ public

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 optional
返回
float|int|null

buffered() ¶ public

buffered(): self

返回一个新集合,其中包含此集合执行的操作。无论新集合迭代多少次,这些操作都只会执行一次。

这也可以用来使任何不可重绕的迭代器可重绕。

返回
self

cartesianProduct() ¶ public

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 optional

一个可调用对象,允许您自定义产品结果。

callable|null $filter optional

一个过滤回调,必须返回 true,结果才能成为最终结果的一部分。

返回
Cake\Collection\CollectionInterface
抛出
LogicException

chunk() ¶ public

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() ¶ public

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 optional
返回
self

combine() ¶ public

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 optional
返回
self

compile() ¶ public

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 optional
返回
self

contains() ¶ public

contains(mixed $value): bool

如果 $value 存在于此集合中,则返回 true。比较同时按值和类型进行。

参数
mixed $value
返回
bool

count() ¶ public

count(): int

返回集合中元素的数量。

警告

将改变迭代器的当前位置。

在您迭代集合(例如在 foreach 循环中)的同时调用此方法会导致未定义的行为。避免这样做。

使用 NoRewindIterator 集合中的所有元素。

在某些类型的集合上,调用此方法可能会导致其在之后无法使用。也就是说,您可能无法从中获取元素或对其进行迭代。

具体来说,任何包装生成器(带有 yield 语句的函数)或未缓冲数据库游标的集合在调用 count() 之后将不再接受任何其他函数调用。

使用 buffered() 方法创建一个新集合来解决此问题。

可能报告的元素数量超过唯一键的数量。

通过将集合附加在一起或内部迭代器返回重复键构建的任何集合,使用此函数报告的元素数量将大于将集合转换为键控数组时的最终元素数量。这是因为重复的键将在最终数组中合并为一个,而此计数方法只关心将其转换为普通列表后的元素数量。

如果您需要在考虑键(唯一键的数量)的情况下计算元素的数量,您可以调用 countKeys()。

返回
int

countBy() ¶ public

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() ¶ public

countKeys(): int

返回此迭代器中唯一键的数量。这与调用 toArray() 后集合中包含的元素数量相同

此方法有一些注意事项。有关详细信息,请参阅 CollectionInterface::count()。

返回
int

current() ¶ public

current(): mixed

返回将所有迭代器的所有元素压缩在一起的结果值,这些元素具有相同的 positional index。

返回
mixed

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 optional
返回
self

first() ¶ public

first(): mixed

返回此集合中的第一个结果

返回
mixed

firstMatch() ¶ public

firstMatch(array $conditions): mixed

返回第一个与条件中列出的所有键值对匹配的结果。

参数
array $conditions
返回
mixed

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 optional

在值分组时是否保留现有集合的键。默认为 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 接口的一部分。

返回
array

key() ¶ public

key(): mixed

实现 Iterator::key()。

返回
mixed

last() ¶ public

last(): mixed

返回此集合中的最后一个结果

返回
mixed

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 optional
callable|string $nestingKey optional
返回
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 optional
返回
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 optional
返回
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 optional
返回
mixed

nest() ¶ public

nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self

返回一个新的集合,其中值根据 id 属性路径和父 id 属性路径嵌套在树状结构中。

参数
callable|string $idPath
callable|string $parentPath
string $nestingKey optional
返回
self

newCollection() ¶ protected

newCollection(mixed ...$args): Cake\Collection\CollectionInterface

返回一个新的集合。

允许使用此特性的类确定其返回的集合接口类型。

参数
mixed ...$args

构造函数参数。

返回
Cake\Collection\CollectionInterface

next() ¶ public

next(): void

实现 Iterator::next()。

返回
void

optimizeUnwrap() ¶ protected

optimizeUnwrap(): Iterator|array

解开此迭代器并返回最简单的可遍历对象,该对象可用于提取数据

返回
Iterator|array

prepend() ¶ public

prepend(mixed $items): self

将一组项目预先添加到集合中以创建新集合

参数
mixed $items
返回
self

prependItem() ¶ public

prependItem(mixed $item, mixed $key = null): self

预先添加单个项目以创建新集合。

参数
mixed $item
mixed $key optional
返回
self

reduce() ¶ public

reduce(callable $callback, mixed $initial = null): mixed

将此集合中的值折叠成单个值,作为将回调函数应用于所有元素的结果。$initial 是减少的初始状态,并且回调函数应返回它的每个后续步骤。如果省略 $initial,则将使用集合的第一个值代替它,并且减少将从第二个项目开始。

参数
callable $callback
mixed $initial optional
返回
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 optional
返回
self

rewind() ¶ public

rewind(): void

实现 Iterator::rewind()。

返回
void

sample() ¶ public

sample(int $length = 10): self

返回一个新集合,其中包含从当前集合中随机选择的 $length 个元素。

参数
int $length 可选
返回
self

shuffle() ¶ public

shuffle(): self

返回一个新集合,其中元素按随机顺序排列,此函数不会保留集合中的原始键。

返回
self

skip() ¶ public

skip(int $length): self

返回一个新集合,它将跳过迭代开始处的指定数量的元素。

参数
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 optional
返回
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 optional
返回
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

toArray() ¶ public

toArray(bool $keepKeys = true): array

返回结果的数组表示。

参数
bool $keepKeys optional
返回
array

toList() ¶ public

toList(): array

返回结果的按数字索引的数组表示。这等同于调用 toArray(false)。

返回
array

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,并且必须返回一个可以连接到最终结果的数组或 Traversable 对象。

如果未传入转换函数,则将使用“标识”函数。当源集合中的每个元素都是要一个接一个地附加的项目列表时,这很有用。

示例

$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 optional
返回
self

unique() ¶ public

unique(callable $callback = null): self

遍历集合中的每个值,并返回一个新集合,其中只包含根据 callback 返回的值而确定的唯一值。

回调函数以 value 作为第一个参数,key 作为第二个参数。

参数
callable $callback optional
返回
self

unwrap() ¶ public

unwrap(): Iterator

返回可以安全遍历而不会丢失任何可能的转换的最接近的嵌套迭代器。这主要用于删除只能减慢迭代过程的空 IteratorIterator 包装器。

返回
Iterator

valid() ¶ public

valid(): bool

实现 Iterator::valid()。

返回
bool

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

属性详细信息

$_callback ¶ protected

用于将项目压缩在一起的函数

类型
callable|null

$_iterators ¶ protected

包含已附加的原始迭代器对象

类型
array

$multipleIterator ¶ protected

类型
MultipleIterator
OpenHub
Pingping
Linode
  • 商业解决方案
  • 展示
  • 文档
  • 书籍
  • API
  • 视频
  • 报告安全问题
  • 隐私政策
  • 标识和商标
  • 社区
  • 参与
  • 问题 (Github)
  • 烘焙坊
  • 精选资源
  • 培训
  • 聚会
  • 我的 CakePHP
  • CakeFest
  • 新闻通讯
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • 帮助和支持
  • 论坛
  • Stack Overflow
  • IRC
  • Slack
  • 付费支持

使用 CakePHP API 文档 生成