具有不同元素的PHP数组(如Python集)

时间:2009-07-22 17:37:23

标签: php arrays

是否有PHP数组类的版本,其中所有元素必须是不同的,例如,在Python中设置?

7 个答案:

答案 0 :(得分:4)

不。您可以使用关联数组伪造它,其中键是“集合”中的元素,并忽略值。

答案 1 :(得分: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 :(得分:2)

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

答案 3 :(得分:1)

数组是一个数组,大多数情况下你可以放任何东西。所有键必须是唯一的。如果你想去添加一个删除重复值的函数,那么只需执行一个array_unique语句就可以了。

答案 4 :(得分:1)

对于非整数和字符串的对象:SplObjectStorage

  

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

答案 5 :(得分:0)

以基本方式尝试array_unique(),这可能有助于避免数组中的重复。

答案 6 :(得分:0)

您可以使用此Set class。你可以用pecl安装

sudo pecl install ds

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

composer require php-ds/php-ds