在PHP中内置对集合的支持


Built in support for sets in PHP?

我正在寻找一种简单的方法来创建一个数组在php中,将不允许重复的条目,但允许其他集合或数组的轻松组合。

我最感兴趣的是这种语言中是否存在这样的特性,因为编写我自己的特性并不困难。如果不需要的话,我只是不想。

只是一个想法,如果你使用数组的键而不是值,你将确保没有重复,这也允许容易合并两个"集"

$set1 = array ('a' => 1, 'b' => 1, );
$set2 = array ('b' => 1, 'c' => 1, );
$union = $set1 + $set2;

答案是否定的,PHP内部没有本地的set解决方案。有一个Set数据结构,但这不是基准PHP。

在任何语言中都有使用映射(即关联数组)实现集合的约定。对于PHP,您应该使用true作为底部值。

<?php
$left = [1=>true, 5=>true, 7=>true];
$right = [6=>true, 7=>true, 8=>true, 9=>true];
$union = $left + $right;
$intersection = array_intersect_assoc($left, $right);
var_dump($left, $right, $union, $intersection);

可以使用array_combine来删除重复项

$cars = array("Volvo", "BMW", "Toyota");
array_push($cars,"BMW");
$map = array_combine($cars, $cars);

我也有这个问题,所以写了一个类:https://github.com/jakewhiteley/php-set-object

如建议,它扩展和ArrayObject,并允许本地感觉插入/迭代/删除值,但没有使用array_unique()任何地方。

实现基于MDN JS Docs for Sets in EMCA 6 JavaScript。

Set类

https://www.php.net/manual/en/class.ds-set.php

不知道什么时候出来

在Laravel中,Collection类中有一个方法unique可能会有所帮助。来自Laravel文档:

$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]