CakePHP
  • 文档
    • 书籍
    • API
    • 视频
    • 报告安全问题
    • 隐私政策
    • 标志 & 商标
  • 商业解决方案
  • 商品
  • 公路旅行
  • 团队
  • 社区
    • 社区
    • 参与进来
    • 问题 (Github)
    • 面包店
    • 特色资源
    • 培训
    • 聚会
    • 我的 CakePHP
    • CakeFest
    • 新闻稿
    • 领英
    • YouTube
    • 脸书
    • 推特
    • 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

类 BufferedIterator

从另一个迭代器创建一个迭代器,该迭代器将内部迭代器的结果保存在内存中,因此不需要重新计算结果。

命名空间: Cake\Collection\Iterator

属性摘要

  • $_buffer 受保护的
    SplDoublyLinkedList<mixed>

    包含来自先前迭代器的结果的内存缓存

  • $_current 受保护的
    混合

    从内部迭代器获取的最后一个记录

  • $_finished 受保护的
    布尔值

    内部迭代器是否已达到其末尾。

  • $_index 受保护的
    整型

    指向应获取的下一个记录号

  • $_key 受保护的
    混合

    从内部迭代器获取的最后一个键

  • $_started 受保护的
    布尔值

    内部迭代器的重绕方法是否已经被调用

方法摘要

  • __construct() 公共的

    维护内部迭代器产生的结果的内存缓存。

  • __debugInfo() 公共的

    返回一个可用于描述此对象内部状态的数组。

  • __serialize() 公共的

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

  • __unserialize() 公共的

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

  • _createMatcherFilter() 受保护的

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

  • _extract() 受保护的

    返回 $data 中的一列,可以通过迭代 $path 中包含的列名称来提取它。它将为用 {*} 表示的元素返回数组

  • _propertyExtractor() 受保护的

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

  • _simpleExtract() 受保护的

    返回 $data 中的一列,可以通过迭代 $path 中包含的列名称来提取它

  • append() 公共的

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

  • appendItem() 公共的

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

  • avg() 公共的

    返回使用 $path 提取的所有值的平均值或此集合的平均值。

  • buffered() 公共的

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

  • cartesianProduct() 公共的

    创建一个新的集合,它是当前集合的笛卡尔积

  • chunk() 公共的

    将集合分解为给定大小的较小数组。

  • chunkWithKeys() 公共的

    将集合分解为给定大小的较小数组。

  • combine() 公共的

    返回一个新的集合,其中包含根据值路径提取的值,然后按键路径索引。可选地,此方法可以根据组属性路径生成父组。

  • compile() 公共的

    迭代此集合中的所有元素一次,并执行所有堆叠的操作,最后返回一个包含结果的新集合。这对于将不可重绕的内部迭代器转换为可以重绕和多次使用的集合很有用。

  • contains() 公共的

    如果 $value 存在于此集合中,则返回 true。比较是通过值和类型进行的。

  • count() 公共的

    返回此集合中项目的数量

  • countBy() 公共的

    将列表排序到组中,并返回每个组中元素数量的计数。类似于 groupBy,但不是返回值列表,而是返回该组中值的计数。

  • countKeys() 公共的

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

  • current() 公共的

    返回迭代器中的当前记录

  • each() 公共的

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

  • every() 公共的

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

  • extract() 公共的

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

  • filter() 公共的

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

  • first() 公共的

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

  • firstMatch() 公共的

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

  • groupBy() 公共的

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

  • indexBy() 公共的

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

  • insert() 公共的

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

  • isEmpty() 公共的

    返回此集合中是否有元素

  • jsonSerialize() 公共的

    返回可以转换为 JSON 的数据。这与 toArray() 返回相同的数据,其中只包含唯一键。

  • key() 公共的

    返回迭代器中的当前键

  • last() 公共的

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

  • lazy() 公共的

    返回一个新的集合,其中任何在它之后链式调用的操作都保证是延迟执行的。也就是说,元素将一次一个地产生。

  • listNested() 公共的

    返回一个新的集合,其中包含此集合的每个元素,在扁平化树结构之后。树结构由将元素嵌套在具有已知名称的键下定义。可以使用 '$nestingKey' 参数指定此名称。

  • map() 公共的

    使用提供的可调用对象修改此集合中的每个值后,返回另一个集合。

  • match() 公共的

    查看列表中的每个值,返回一个包含所有包含 $conditions 中列出的所有键值对的值的 Collection。

  • max() 公共的

    在按属性排序后,返回此集合中的顶层元素。有关回调和 $sort 参数的信息,请查看 sortBy 方法

  • median() 公共的

    返回使用 $path 提取的所有值的中间值或此集合的中间值。

  • min() 公共的

    在按属性排序后,返回此集合中的底层元素。有关回调和 $sort 参数的信息,请查看 sortBy 方法

  • nest() 公共的

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

  • newCollection() 受保护的

    返回一个新的集合。

  • next() public

    将迭代器指针移至下一个元素

  • optimizeUnwrap() protected

    展开此迭代器并返回可用于获取数据的最简单的可遍历对象

  • prepend() public

    将一组项目添加到集合的开头,创建一个新的集合

  • prependItem() public

    添加一个单一项目到集合的开头,创建一个新的集合。

  • reduce() public

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

  • reject() public

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

  • rewind() public

    将集合重新设置为开头

  • sample() public

    从这个集合中返回一个包含最多 $length 个随机元素的新集合

  • shuffle() public

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

  • skip() public

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

  • some() public

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

  • sortBy() public

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

  • stopWhen() public

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

  • 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

    返回迭代器是否还有更多元素

  • zip() public

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

  • zipWith() public

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

方法详情

__construct() ¶ public

__construct(iterable $items)

维护内部迭代器产生的结果的内存缓存。

参数
iterable $items

要过滤的项目。

__debugInfo() ¶ public

__debugInfo(): array<string, mixed>

返回一个可用于描述此对象内部状态的数组。

返回值
array<string, mixed>

__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

要提取的路径。

返回值
混合

_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

要提取的路径。

返回值
混合

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
返回值
布尔值

count() ¶ public

count(): int

返回此集合中项目的数量

警告

将改变迭代器的当前位置

在遍历集合的同时调用此方法(例如在 foreach 中),会导致未定义的行为。避免这样做。

对于 NoRewindIterator 集合,将消耗所有元素

对于某些类型的集合,调用此方法之后可能无法使用。也就是说,你可能无法从其中获取元素,或者无法再对其进行迭代。

特别是,任何包含 Generator(带有 yield 语句的函数)或未缓冲的数据库游标的集合,在调用 `count()` 方法之后,将不再接受任何其他函数调用。

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

可能报告的元素数量多于唯一键的数量

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

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

返回值
整型

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()`。

返回值
整型

current() ¶ public

current(): 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
返回值
布尔值

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

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

返回值
混合

firstMatch() ¶ public

firstMatch(array $conditions): mixed

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

参数
array $conditions
返回值
混合

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
返回值
布尔值

jsonSerialize() ¶ public

jsonSerialize(): array

返回可以转换为 JSON 的数据。这与 toArray() 返回相同的数据,其中只包含唯一键。

JsonSerializable 接口的一部分。

返回值
array

key() ¶ public

key(): mixed

返回迭代器中的当前键

返回值
混合

last() ¶ public

last(): 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
返回值
混合

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
返回值
混合

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() ¶ 受保护的

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

返回一个新的集合。

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

参数
混合 ...$args

构造函数参数。

返回值
Cake\Collection\CollectionInterface

next() ¶ 公共的

next(): void

将迭代器指针移至下一个元素

返回值
void

optimizeUnwrap() ¶ 受保护的

optimizeUnwrap(): Iterator|array

展开此迭代器并返回可用于获取数据的最简单的可遍历对象

返回值
迭代器|数组

prepend() ¶ 公共的

prepend(mixed $items): self

将一组项目添加到集合的开头,创建一个新的集合

参数
混合 $items
返回值
self

prependItem() ¶ 公共的

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

添加一个单一项目到集合的开头,创建一个新的集合。

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

reduce() ¶ 公共的

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

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

参数
callable $callback
混合 $initial 可选的
返回值
混合

reject() ¶ 公共的

reject(callable $callback = null): self

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

每次执行回调函数时,它将接收当前迭代中元素的值、元素的键以及此集合作为参数,按此顺序。

示例

从数组中过滤偶数,最终结果集合中只保留 1 和 3。

$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
 return $value % 2 === 0;
});
参数
可调用 $callback 可选的
返回值
self

rewind() ¶ 公共的

rewind(): void

将集合重新设置为开头

返回值
void

sample() ¶ 公共的

sample(int $length = 10): self

从这个集合中返回一个包含最多 $length 个随机元素的新集合

参数
整型 $length 可选的
返回值
self

shuffle() ¶ 公共的

shuffle(): self

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

返回值
self

skip() ¶ 公共的

skip(int $length): self

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

参数
整型 $length
返回值
self

some() ¶ 公共的

some(callable $callback): bool

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

回调函数会传递正在测试的元素的值和键,如果测试通过,则应返回 true。

示例

$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
 return $value < 21;
});
参数
callable $callback
返回值
布尔值

sortBy() ¶ 公共的

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
整型 $order 可选的
int $sort optional
返回值
self

stopWhen() ¶ 公共的

stopWhen(callable|array $condition): self

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

这对于处理无限迭代器或在某个点开始返回无效元素的任何生成器很有用。例如,在从文件流中读取行时,您可能希望在达到某个值后停止迭代。

示例

获取 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]);
参数
可调用|数组 $condition
返回值
self

sumOf() ¶ 公共的

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
返回值
浮点数|整型

take() ¶ 公共的

take(int $length = 1, int $offset = 0): self

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

参数
整型 $length 可选的
整型 $offset 可选的
返回值
self

takeLast() ¶ 公共的

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];
参数
整型 $length
返回值
self

through() ¶ 公共的

through(callable $callback): self

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

示例

$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
     return new MyCustomCollection($collection);
});
参数
callable $callback
返回值
self

toArray() ¶ 公共的

toArray(bool $keepKeys = true): array

返回结果的数组表示

参数
bool $keepKeys optional
返回值
array

toList() ¶ 公共的

toList(): array

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

返回值
array

transpose() ¶ 公共的

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() ¶ 公共的

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

unique() ¶ 公共的

unique(callable $callback = null): self

循环遍历集合中的每个值,并返回一个新的集合,其中只包含基于 callback 返回的值的唯一值。

回调函数将 value 作为第一个参数传递,将 key 作为第二个参数传递。

参数
可调用 $callback 可选的
返回值
self

unwrap() ¶ 公共的

unwrap(): Iterator

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

返回值
Iterator

valid() ¶ 公共的

valid(): bool

返回迭代器是否还有更多元素

返回值
布尔值

zip() ¶ 公共的

zip(iterable ...$items): self

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

示例

$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
参数
可迭代 ...$items
返回值
self

zipWith() ¶ 公共的

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

属性详细信息

$_buffer ¶ 受保护的

包含来自先前迭代器的结果的内存缓存

类型
SplDoublyLinkedList<mixed>

$_current ¶ 受保护的

从内部迭代器获取的最后一个记录

类型
混合

$_finished ¶ 受保护的

内部迭代器是否已达到其末尾。

类型
布尔值

$_index ¶ 受保护的

指向应获取的下一个记录号

类型
整型

$_key ¶ 受保护的

从内部迭代器获取的最后一个键

类型
混合

$_started ¶ 受保护的

内部迭代器的重绕方法是否已经被调用

类型
布尔值
OpenHub
Pingping
Linode
  • 商业解决方案
  • 展示
  • 文档
  • 书籍
  • API
  • 视频
  • 报告安全问题
  • 隐私政策
  • 标志 & 商标
  • 社区
  • 参与进来
  • 问题 (Github)
  • 面包店
  • 特色资源
  • 培训
  • 聚会
  • 我的 CakePHP
  • CakeFest
  • 新闻稿
  • 领英
  • YouTube
  • 脸书
  • 推特
  • Mastodon
  • 帮助 & 支持
  • 论坛
  • Stack Overflow
  • IRC
  • Slack
  • 付费支持

使用 CakePHP API 文档 生成