php集合实现
PHP 集合实现方法
在 PHP 中,集合(Collection)通常指一组有序、可操作的数据结构。可以通过原生数组或专门设计的类库(如 Laravel 的 Illuminate\Support\Collection)实现集合功能。以下是几种常见的实现方式:
使用原生数组实现集合
PHP 数组本身支持动态增删元素和多种操作函数,可作为简单集合使用:
$collection = [1, 2, 3, 4];
// 添加元素
$collection[] = 5;
// 过滤
$filtered = array_filter($collection, fn($item) => $item % 2 === 0);
// 映射
$mapped = array_map(fn($item) => $item * 2, $collection);
使用 Laravel Collection
Laravel 提供的 Collection 类封装了丰富的链式操作方法:
use Illuminate\Support\Collection;
$collection = new Collection([1, 2, 3]);
// 链式操作
$result = $collection->filter(fn($item) => $item > 1)
->map(fn($item) => $item * 2);
自定义集合类
如需独立于框架,可自行实现集合类:
class CustomCollection implements IteratorAggregate {
private $items = [];
public function __construct(array $items) {
$this->items = $items;
}
public function filter(callable $callback): self {
return new self(array_filter($this->items, $callback));
}
public function getIterator(): ArrayIterator {
return new ArrayIterator($this->items);
}
}
关键操作对比
| 操作类型 | 原生数组 | Laravel Collection |
|---|---|---|
| 过滤 | array_filter |
->filter() |
| 映射 | array_map |
->map() |
| 聚合 | array_reduce |
->reduce() |
| 排序 | sort()/usort() |
->sort()/->sortBy() |
性能考量
- 原生数组操作性能更高,适合简单场景
- 集合类代码可读性更强,适合复杂业务逻辑
- Laravel Collection 会额外加载依赖,非 Laravel 项目需权衡成本
选择方案时应根据项目需求平衡开发效率与运行时性能。







