带类的数组:检查唯一性

时间:2017-11-05 19:01:27

标签: php

我有一组类,我需要过滤它们是否在数组中是唯一的。

我的方法:

public function unique() {
    $uniqueStreams = [];

    foreach($this->streams as $stream) {
        if(!in_array($stream, $uniqueStreams)) {
            $uniqueStreams[] = $stream;
        }
    }

    return new static($uniqueStreams);
}

问题是,in_array只检查该类名的存在(至少这是我所探索过的),但我需要确保它们不相同(希望它们实例来自同一个类。)

1 个答案:

答案 0 :(得分:1)

正如@u_mulder所说,序列化它们并比较字符串正在解决这个挑战!

public function unique() {
    $uniqueStreams = [];

    foreach($this->streams as $stream) {
        $serialized = serialize($stream);
        if(!in_array($serialized, $uniqueStreams)) {
            $uniqueStreams[] = $serialized;
        }
    }

    foreach($uniqueStreams as &$uniqueStream) {
        $uniqueStream = unserialize($uniqueStream);
    }

    return new static($uniqueStreams);
}