Answer the question
In order to leave comments, you need to log in
How to uniqueize an array of object references by the references themselves, and not by the value of the objects?
$a = 1;
$b = 2;
$array[] = &$a; // Два элемента - ссылка на $a
$array[] = &$a;
$array[] = &$b; // Один элемент - ссылка на $b
$array[0]++;
// Естественно изменилось и значение $array[1]:
print_r($array);
// Array ( [0] => 2 [1] => 2 [2] => 2 )
print_r(array_unique($array));
// Array ( [0] => 2 )
// Из трех ссылок, две из которых уникальны, осталась только одна
$array[0] === $array[1] // true
$array[0] === $array[2] // true :(
function is_ref_to(&$a, &$b)
{
$t = $a;
if($r=($b===($a=1))){ $r = ($b===($a=0)); }
$a = $t;
return $r;
}
Answer the question
In order to leave comments, you need to log in
Write your own version of array_unique, because the comparison inside the library is based on string values - (string)s1 == (string)s2.
spl_object_hash won't work?
There will be something like:
$id = spl_object_hash($a);
$array[$id] = $a;
$s = new SplObjectStorage();
$o1 = new StdClass;
$o1->a = 1;
$o2 = new StdClass;
$o2->a = 1;
$o3 = new StdClass;
$o3->b = 3;
$s->attach($o1);
$s->attach($o2);
$s->attach($o1);
$s->attach($o3);
var_dump(iterator_to_array($s));
array(3) {
[0]=>
object(stdClass)#2 (1) {
["a"]=>
int(1)
}
[1]=>
object(stdClass)#3 (1) {
["a"]=>
int(1)
}
[2]=>
object(stdClass)#4 (1) {
["b"]=>
int(3)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question