php实现集合
PHP实现集合操作
在PHP中,可以通过数组或特定类来实现集合操作。以下是几种常见方法:
使用数组实现集合 PHP数组天然支持集合操作,可通过内置函数实现:
$set1 = [1, 2, 3];
$set2 = [2, 3, 4];
// 并集
$union = array_unique(array_merge($set1, $set2));
// 交集
$intersection = array_intersect($set1, $set2);
// 差集
$difference = array_diff($set1, $set2);
使用SplObjectStorage类 对于对象集合,SplObjectStorage更高效:

$storage = new SplObjectStorage();
$obj1 = new stdClass();
$obj2 = new stdClass();
$storage->attach($obj1);
$storage->attach($obj2);
$storage->detach($obj1);
自定义集合类 创建专门的集合类可提供更丰富的操作:
class Set implements IteratorAggregate {
private $elements = [];
public function add($element) {
if (!in_array($element, $this->elements)) {
$this->elements[] = $element;
}
}
public function getIterator() {
return new ArrayIterator($this->elements);
}
}
使用第三方库 Doctrine Collections等库提供完整集合实现:

use Doctrine\Common\Collections\ArrayCollection;
$collection = new ArrayCollection([1, 2, 3]);
$filtered = $collection->filter(function($n) {
return $n > 1;
});
性能考虑
- 小规模数据使用数组足够高效
- 大规模数据建议使用专门集合类
- 对象集合优先考虑SplObjectStorage
不可变集合实现 通过返回新实例实现不可变性:
public function add($element) {
$new = clone $this;
$new->elements[] = $element;
return $new;
}






