是否有PHP数组类的版本,其中所有元素必须是唯一的,例如Python中的集合?
不行。您可以通过使用关联数组来伪造,其中键是“集”中的元素,值被忽略。
<?php
class DistinctArray implements IteratorAggregate, Countable, ArrayAccess
{
protected $store = array();
public function __construct(array $initialValues)
{
foreach ($initialValues as $key => $value) {
$this[$key] = $value;
}
}
final public function offsetSet( $offset, $value )
{
if (in_array($value, $this->store, true)) {
throw new DomainException('Values must be unique!');
}
if (null === $offset) {
array_push($this->store, $value);
} else {
$this->store[$offset] = $value;
}
}
final public function offsetGet($offset)
{
return $this->store[$offset];
}
final public function offsetExists($offset)
{
return array_key_exists($offset, $this->store);
}
final public function offsetUnset($offset)
{
unset( $this->store[$offset] );
}
final public function count()
{
return count($this->store);
}
final public function getIterator()
{
return new ArrayIterator($this->store);
}
}
$test = new DistinctArray(array(
'test' => 1,
'foo' => 2,
'bar' => 3,
'baz' => '1',
8 => 4,
));
try {
$test[] = 5;
$test[] = 6;
$test['dupe'] = 1;
}
catch (DomainException $e) {
echo "Oops! ", $e->getMessage(), "<hr>";
}
foreach ($test as $value) {
echo $value, '<br>';
}
数组就是数组,大多数情况下你可以把任何东西放进去。所有的键必须是唯一的。如果你想添加一个函数来剔除重复的值,那么只需使用 array_unique 语句即可实现。
SplObjectStorage 类提供了从对象到数据的映射,或者通过忽略数据,提供一个对象集合。
sudo pecl install ds
如果您没有 root 访问权限,也可以使用 polyfill 版本。
composer require php-ds/php-ds
你不能使用 array_unique。
如果你使用 int 和 string 值,array_unique 会使用字符串表示进行比较,所以数组 [1,'1','2'] 将会得到 [1,'2']。
你可以使用一些技巧
数组键索引是唯一的。
因此,您可以将唯一值存储为字符串键,就像 Python 集合一样。
$liste 只是模拟数据的一个糟糕示例。
$liste = ['1','1','2','3','4'];
$uniq = [];
for ($liste as elem) {
$uniq[$elem] = 1;
}
$uniq = array_keys($uniq);
// Or use directly
for ($uniq as $uniqVal => $null) {
echo $uniqVal;
}
array_unique(),也许这可以帮助避免数组中的重复项。