php集合实现
PHP 集合实现方法
在 PHP 中,集合(Collection)通常指一组有序或无序的数据结构,用于存储多个元素。可以通过数组、对象或专用库实现集合功能。
使用原生数组实现集合
PHP 数组天然支持集合操作,包括添加、删除、遍历和过滤等。
$collection = [1, 2, 3, 4, 5];
// 添加元素
$collection[] = 6;
// 删除元素
unset($collection[0]);
// 遍历
foreach ($collection as $item) {
echo $item;
}
使用 SPL(标准 PHP 库)实现集合
SPL 提供了一些内置类,如 ArrayObject,可以封装数组并提供更多方法。
$collection = new ArrayObject([1, 2, 3]);
// 添加元素
$collection->append(4);
// 删除元素
$collection->offsetUnset(0);
使用第三方库实现高级集合
Laravel 的 Illuminate\Support\Collection 提供了丰富的集合操作方法。
use Illuminate\Support\Collection;
$collection = new Collection([1, 2, 3]);
// 过滤
$filtered = $collection->filter(function ($item) {
return $item > 1;
});
// 映射
$mapped = $collection->map(function ($item) {
return $item * 2;
});
自定义集合类
可以创建一个自定义类封装集合操作,提供更灵活的功能。
class CustomCollection {
private $items = [];
public function add($item) {
$this->items[] = $item;
}
public function remove($key) {
unset($this->items[$key]);
}
public function all() {
return $this->items;
}
}
$collection = new CustomCollection();
$collection->add(1);
$collection->add(2);
集合的常见操作
- 过滤:使用
array_filter或自定义方法筛选元素。 - 映射:使用
array_map转换集合中的每个元素。 - 归约:使用
array_reduce将集合合并为单个值。 - 排序:使用
sort、usort等方法对集合排序。
$numbers = [1, 2, 3, 4, 5];
// 过滤偶数
$evens = array_filter($numbers, function ($n) {
return $n % 2 === 0;
});
// 平方映射
$squares = array_map(function ($n) {
return $n * $n;
}, $numbers);
// 求和归约
$sum = array_reduce($numbers, function ($carry, $n) {
return $carry + $n;
}, 0);
通过以上方法,可以在 PHP 中灵活实现集合功能,根据需求选择原生数组、SPL 或第三方库。







