php array 实现set
使用 array_unique 函数去重
PHP 的 array_unique 函数可以移除数组中的重复值,保留唯一的元素。这是实现 Set 功能最简单的方法。示例代码:
$array = [1, 2, 2, 3, 4, 4];
$uniqueArray = array_unique($array);
// 结果: [1, 2, 3, 4]
使用 array_keys 和 array_flip 组合
这种方法利用键名的唯一性特性。先将数组值转为键名,再翻转回来:
$array = ['a', 'b', 'b', 'c'];
$uniqueArray = array_keys(array_flip($array));
// 结果: ['a', 'b', 'c']
自定义 Set 类封装
创建一个封装类来模拟 Set 数据结构:
class Set {
private $elements = [];
public function add($item) {
if (!in_array($item, $this->elements)) {
$this->elements[] = $item;
}
}
public function remove($item) {
$index = array_search($item, $this->elements);
if ($index !== false) {
unset($this->elements[$index]);
}
}
public function contains($item) {
return in_array($item, $this->elements);
}
public function toArray() {
return array_values($this->elements);
}
}
使用 SplObjectStorage 处理对象集合
当需要存储对象时,SplObjectStorage 提供高效的解决方案:
$set = new SplObjectStorage();
$obj1 = new stdClass();
$obj2 = new stdClass();
$set->attach($obj1);
$set->attach($obj2);
$set->attach($obj1); // 不会重复添加
利用关联数组模拟 Set 操作
通过键值对实现基本 Set 操作:

$set = [];
$set['key1'] = true; // 添加元素
unset($set['key1']); // 移除元素
isset($set['key1']); // 检查存在性






