对象的array_unique? [英] array_unique for objects?
问题描述
有没有像对象的array_unique这样的方法?我有一堆带有我合并的角色"对象的数组,然后我想取出重复项:)
Is there any method like the array_unique for objects? I have a bunch of arrays with 'Role' objects that I merge, and then I want to take out the duplicates :)
推荐答案
好吧,array_unique()
比较元素的字符串值:
Well, array_unique()
compares the string value of the elements:
注意:当且仅当 (string) $elem1 === (string) $elem2
即当字符串表示相同时,才认为两个元素相等,将使用第一个元素.
Note: Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2
i.e. when the string representation is the same, the first element will be used.
所以一定要实现__toString()
类中的方法,并且它为相同的角色输出相同的值,例如
So make sure to implement the __toString()
method in your class and that it outputs the same value for equal roles, e.g.
class Role {
private $name;
//.....
public function __toString() {
return $this->name;
}
}
如果两个角色具有相同的名称,这将认为它们是平等的.
This would consider two roles as equal if they have the same name.
这篇关于对象的array_unique?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!