我有一组类,我需要过滤它们是否在数组中是唯一的。
我的方法:
public function unique() {
$uniqueStreams = [];
foreach($this->streams as $stream) {
if(!in_array($stream, $uniqueStreams)) {
$uniqueStreams[] = $stream;
}
}
return new static($uniqueStreams);
}
问题是,in_array
只检查该类名的存在(至少这是我所探索过的),但我需要确保它们不相同(希望它们实例来自同一个类。)
答案 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);
}