3

I have an object like this:

class FanStruct{
    public $date; 
    public $userid;

    function __construct($date, $id){
        $this->date = $date;
        $this->userid = $id;
    }
}

I have maximum of 30 of them in an array, and they are sorted by $userid.

What is the best way to go though the array, and remove duplicate objects based on $userid (ignoring $date)?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Malfist
  • 31,179
  • 61
  • 182
  • 269
  • Although this is an old question and there's already a good accepted answer, it's worth mention you can (and should) use SORT_REGULAR as explained here: http://stackoverflow.com/a/18203564/1412157 – LucaM Apr 07 '16 at 08:23

2 Answers2

8

Here's a simple test that at least should get you started. Your __toString method might need to be more elaborate to generate uniqueness for your instances of FanStruct

<?php

class FanStruct{
    public $date;
    public $userid;

    function __construct($date, $id){
        $this->date = $date;
        $this->userid = $id;
    }

    public function __toString()
    {
      return $this->date . $this->userid;
    }
}

$test = array(
  new FanStruct( 'today', 1 )
  ,new FanStruct( 'today', 1 )
  ,new FanStruct( 'tomorrow', 1 )
);

print_r( array_unique( $test ) );

?>
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • Since 5.2.9 you don't need the `__toString()` anymore, it will work based on `(object)$x == (object)$y` comparisons when you use `SORT_REGULAR`. – Ja͢ck Aug 15 '13 at 11:07
1
$temp = array($fans[$x]);
for(var $x=1;$x<sizeof($fans);$x++) {
  if ($fans[$x]->userid != $fans[$x]->userid)
     $temp[] = $fans[$x];
}

Requires a temporary variable, but works.

cgp
  • 41,026
  • 12
  • 101
  • 131