PHP数组的独特元素(类似于Python的set)

5

是否有PHP数组类的版本,其中所有元素必须是唯一的,例如Python中的集合?

9个回答

6

不行。您可以通过使用关联数组来伪造,其中键是“集”中的元素,值被忽略。


2
请注意,这仅适用于字符串和数字,因为这些是数组键的唯一合法类型。您不能通过这种方式拥有对象的“集合”。 - soulmerge
这是Lua通常的做法。当然,Lua表可以使用任何值作为键,而不是仅限于数字和字符串。 - Javier
5
在Lua中完成某事与在PHP中完成该事情无关。 - markh

4
这里是一个初稿,它可能最终适用于你想要的内容。
<?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>';
}

2
你可以使用特殊的类或array_unique来过滤重复项。

1

数组就是数组,大多数情况下你可以把任何东西放进去。所有的键必须是唯一的。如果你想添加一个函数来剔除重复的值,那么只需使用 array_unique 语句即可实现。


1
对于不是整数或字符串的对象:SplObjectStorage

SplObjectStorage 类提供了从对象到数据的映射,或者通过忽略数据,提供一个对象集合。


1
对象从来不是整数或字符串。它们就是对象 ;) - Gordon

1
你可以使用这个 设置类。你可以通过 pecl 安装。
sudo pecl install ds

如果您没有 root 访问权限,也可以使用 polyfill 版本

composer require php-ds/php-ds

0

你不能使用 array_unique。

如果你使用 int 和 string 值,array_unique 会使用字符串表示进行比较,所以数组 [1,'1','2'] 将会得到 [1,'2']


0

你可以使用一些技巧

数组键索引是唯一的。

因此,您可以将唯一值存储为字符串键,就像 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;
}

1
如果数组的值是对象(或数组),它将无法工作,因为对象不能作为键。 - Eden Moshe
是的,"yes"代表真,我在考虑使用"string"作为键。 - PetitCitron

0
以基本的方式,您可以尝试使用array_unique(),也许这可以帮助避免数组中的重复项。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,