CakePHP
  • 文档
    • 书籍
    • API
    • 视频
    • 报告安全问题
    • 隐私政策
    • 标识和商标
  • 商业解决方案
  • 周边商品
  • 旅行
  • 团队
  • 社区
    • 社区
    • 参与
    • 问题 (Github)
    • Bakery
    • 精选资源
    • 培训
    • 聚会
    • 我的 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

类 NestIterator

一种能够识别嵌套项并提供检查或检索嵌套项方法的集合类型

命名空间: Cake\Collection\Iterator

属性摘要

  • $_nestKey protected
    callable|string

    每个元素中包含嵌套项的属性名称

方法摘要

  • __construct() public

    构造函数

  • __debugInfo() public

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

  • __serialize() public

    返回一个用于序列化此对象的数组。

  • __unserialize() public

    重建 Collection 实例。

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

  • each() public

    对此集合中的元素应用回调函数。

  • every() public

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

  • extract() public

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

  • filter() public

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

  • first() public

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

  • firstMatch() public

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

  • getChildren() public

    返回一个可遍历对象,其中包含当前项目的子项。

  • groupBy() public

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

  • hasChildren() public

    如果在当前项目的配置的 nestKey 下存储了数组或可遍历对象,则返回 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() 受保护

    返回一个新的集合。

  • optimizeUnwrap() 受保护

    解包此迭代器并返回最简单的可遍历对象,可用于获取数据。

  • prepend() 公共

    将一组项预置到集合中,创建一个新的集合。

  • prependItem() 公共

    预置一个单项,创建一个新的集合。

  • reduce() 公共

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

  • reject() 公共

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

  • sample() 公共

    返回一个新的集合,其中包含来自此集合的最大 $length 个随机元素。

  • shuffle() 公共

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

  • skip() 公共

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

  • some() 公共

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

  • sortBy() 公共

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

  • stopWhen() 公共

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

  • sumOf() 公共

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

  • take() 公共

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

  • takeLast() 公共

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

  • through() 公共

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

  • toArray() 公共

    返回结果的数组表示。

  • toList() 公共

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

  • transpose() 公共

    将行和列转置为列和行。

  • unfold() 公共

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

  • unique() 公共

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

  • unwrap() 公共

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

  • zip() 公共

    使用它们的索引位置作为参考,将此集合的元素与传递的可迭代对象中的每个元素组合。

  • zipWith() 公共

    使用它们的索引位置作为参考,将此集合的元素与传递的可迭代对象中的每个元素组合。

方法详情

__construct() ¶ 公共

__construct(iterable $items, callable|string $nestKey)

构造函数

参数
iterable $items

集合项。

callable|string $nestKey

包含嵌套项的属性。如果传递可调用对象,它应该返回传递项的子项。

__debugInfo() ¶ 公共

__debugInfo(): array<string, mixed>

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

返回
array<string, mixed>

__serialize() ¶ 公共

__serialize(): array

返回一个用于序列化此对象的数组。

返回
数组

__unserialize() ¶ 公共

__unserialize(array $data): void

重建 Collection 实例。

参数
array $data

数据数组。

返回
void

_createMatcherFilter() ¶ 受保护

_createMatcherFilter(array $conditions): Closure

返回一个接收一个值并返回其是否满足特定条件的可调用对象。

参数
array $conditions

一个键值对条件列表,用于匹配,其中键是要从当前项获取的属性路径,而值是要与项进行比较的值。

返回
闭包

_extract() ¶ 受保护

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

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

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

数据。

list<string> $parts

要从中提取的路径。

返回
混合

_propertyExtractor() ¶ 受保护

_propertyExtractor(callable|string $path): Closure

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

参数
callable|string $path

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

返回
闭包

_simpleExtract() ¶ 受保护

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

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

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

数据。

list<string> $parts

要从中提取的路径。

返回
混合

append() ¶ 公共

append(iterable $items): self

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

参数
iterable $items
返回
自身

appendItem() ¶ 公共

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

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

参数
mixed $item
mixed $key 可选
返回
自身

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

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

这也可用于使任何不可回溯迭代器可回溯。

返回
自身

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
返回
自身

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 可选
返回
自身

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 可选
返回
自身

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 可选
返回
自身

contains() ¶ public

contains(mixed $value): bool

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

参数
mixed $value
返回
bool

count() ¶ public

count(): int

返回集合中元素的数量。

警告

将更改迭代器的当前位置

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

消耗所有 NoRewindIterator 集合的元素

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

特别是任何包装 Generator(具有 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
返回
自身

countKeys() ¶ public

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
返回
自身

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
返回
自身

first() ¶ public

first(): mixed

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

返回
混合

firstMatch() ¶ public

firstMatch(array $conditions): mixed

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

参数
array $conditions
返回
混合

getChildren() ¶ public

getChildren(): RecursiveIterator<mixed, mixed>

返回一个可遍历对象,其中包含当前项目的子项。

返回
RecursiveIterator<mixed, 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

hasChildren() ¶ public

hasChildren(): bool

如果在当前项目的配置的 nestKey 下存储了数组或可遍历对象,则返回 true。

返回
bool

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
返回
自身

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
返回
自身

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 接口的一部分。

返回
数组

last() ¶ public

last(): mixed

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

返回
混合

lazy() ¶ public

lazy(): 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
返回
自身

map() ¶ public

map(callable $callback): self

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

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

示例

获取一个布尔值集合,其中 true 表示一个人是女性

$collection = (new Collection($people))->map(function ($person, $key) {
 return $person->gender === 'female';
});
参数
callable $callback
返回
自身

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
返回
自身

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 可选
返回
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 可选
返回
自身

newCollection() ¶ protected

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

返回一个新的集合。

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

参数
mixed ...$args

构造函数参数。

返回
Cake\Collection\CollectionInterface

optimizeUnwrap() ¶ protected

optimizeUnwrap(): Iterator|array

解包此迭代器并返回最简单的可遍历对象,可用于获取数据。

返回
Iterator|array

prepend() ¶ public

prepend(mixed $items): self

将一组项预置到集合中,创建一个新的集合。

参数
mixed $items
返回
自身

prependItem() ¶ public

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

预置一个单项,创建一个新的集合。

参数
mixed $item
mixed $key 可选
返回
自身

reduce() ¶ public

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

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

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

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 可选
返回
自身

sample() ¶ public

sample(int $length = 10): self

返回一个新的集合,其中包含来自此集合的最大 $length 个随机元素。

参数
int $length 可选
返回
自身

shuffle() ¶ public

shuffle(): self

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

返回
自身

skip() ¶ public

skip(int $length): self

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

参数
int $length
返回
自身

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
返回
自身

stopWhen() ¶ public

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]);
参数
callable|array $condition
返回
自身

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 可选
返回
自身

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
返回
自身

through() ¶ public

through(callable $callback): self

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

示例

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

toArray() ¶ public

toArray(bool $keepKeys = true): array

返回结果的数组表示。

参数
bool $keepKeys 可选
返回
数组

toList() ¶ public

toList(): array

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

返回
数组

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 optional
返回
自身

unique() ¶ public

unique(callable $callback = null): self

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

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

参数
callable $callback 可选
返回
自身

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
返回
自身

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
返回
自身

属性细节

$_nestKey ¶ protected

每个元素中包含嵌套项的属性名称

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

使用 CakePHP API 文档 生成