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
    • 缓存
    • 集合
      • 迭代器
    • 命令
    • 控制台
    • 控制器
    • 核心
    • 数据库
    • 数据源
    • 错误
    • 事件
    • 表单
    • Http
    • I18n
    • 日志
    • 邮件
    • 网络
    • ORM
    • 路由
    • 测试套件
    • 实用程序
    • 验证
    • 视图

类树迭代器

用于扁平化嵌套结构的递归迭代器,也公开所有 Collection 方法

命名空间: Cake\Collection\Iterator

属性摘要

  • $_mode protected
    int

    迭代模式

方法摘要

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

  • each() public

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

  • every() public

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

  • extract() public

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

  • filter() public

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

  • first() public

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

  • firstMatch() public

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

  • groupBy() public

    将集合分成多个集合,根据将每个值通过回调运行的结果进行分组。如果 $callback 是一个字符串而不是一个可调用函数,则根据每个值的 $callback 指定的属性进行分组。

  • 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() protected

    解开此迭代器,并返回可以用来获取数据的最简单的可遍历对象

  • prepend() public

    将一组项目追加到集合,创建一个新的集合

  • prependItem() public

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

  • printer() public

    返回另一个迭代器,该迭代器将返回准备显示给用户的数值。它通过从每个元素中提取一个属性并用空格作为前缀来实现这一点,这样就可以可视化树中的相对位置。

  • reduce() public

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

  • reject() public

    遍历集合中的每个值,并返回另一个不通过真值测试的所有值的集合。这与 filter 相反。

  • 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 包装器。

  • zip() public

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

  • zipWith() public

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

方法详情

__construct() ¶ public

__construct(RecursiveIterator<mixed, mixed> $items, int $mode = RecursiveIteratorIterator::SELF_FIRST, int $flags = 0)

构造函数

参数
RecursiveIterator<mixed, mixed> $items

要展平的迭代器。

int $mode optional

迭代器模式。

int $flags optional

迭代器标志。

_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

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

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

参数
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

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

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

printer() ¶ public

printer(callable|string $valuePath, callable|string|null $keyPath = null, string $spacer = '__'): Cake\Collection\Iterator\TreePrinter

返回另一个迭代器,该迭代器将返回准备显示给用户的数值。它通过从每个元素中提取一个属性并用空格作为前缀来实现这一点,这样就可以可视化树中的相对位置。

$valuePath 和 $keyPath 都可以是一个包含要提取的属性名称的字符串,或者是一个由点分隔的属性路径,这些属性应该依次遵循,以获取路径中的最后一个属性。

或者,$valuePath 和 $keyPath 可以是可调用函数。它们将获取当前元素作为第一个参数,获取当前迭代键作为第二个参数,并将迭代器实例作为第三个参数。

示例

 $printer = (new Collection($treeStructure))->listNested()->printer('name');

使用闭包

 $printer = (new Collection($treeStructure))
     ->listNested()
     ->printer(function ($item, $key, $iterator) {
         return $item->name;
     });
参数
callable|string $valuePath

要提取的属性或返回显示值的函数

callable|string|null $keyPath optional

用作迭代键的属性或返回键值的函数。

string $spacer optional

用于根据树中元素的深度为值添加前缀的字符串

返回值
Cake\Collection\Iterator\TreePrinter

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

sample() ¶ public

sample(int $length = 10): self

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

参数
int $length optional
返回值
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 optional
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,按此顺序,它必须返回一个数组或一个可遍历的对象,该对象可以连接到最终结果。

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

示例

$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 包装器。

返回值
迭代器

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

属性详情

$_mode ¶ protected

迭代模式

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

使用 CakePHP API 文档 生成