I am just finishing a search class and I need to be able to remove duplicate objects from an array. Unique doesn't work for this and I have almost finished a sort function:

for ($i = 0; isset($this->resultArray[$i]); $i++) {
				$c = 0;
				for($c = 0; $i > $c; $c++) {
					if ($this->resultArray[$i]->ID == $this->resultArray[$c]->ID) {

Now how do I complete this so that the duplicate element will be removed from the array?

Regards.

Steve.

    I take it that "uniqueness" depends only on the ID? (I.e., that property is serving as a unique identifier?)

    $temp_uids=array();
    $unique_results = array();
    foreach($this->resultArray as $result)
    {  if(!in_array($result->ID,$temp_uids))
       { $temp_uids[]=$result->ID;
          $unique_results[]=$result;
       }
    }
    $this->resultArray = $unique_results;
    unset($temp_uids, $unique_results);
    

    is my first guess.

    It would be nice if array_unique() could be passed a callback function, à la usort(), wouldn't it?

      I have managed to sort it out anyhow using the unset() function, which I had completely forgotten about.

      for ($i = 0; isset($this->resultArray[$i]); $i++) { // remove any duplicates from the result array
      				$c = 0;
      				for($c = 0; $i > $c; $c++) {
      					if ($this->resultArray[$i]->ID == $this->resultArray[$c]->ID) {
      						unset($this->resultArray[$i]);
      					}
      				}
      			}
      

      Cheers for your help though.

      Regards.

      Steve.

        Righty-ho; I'd just suggest unsetting resultArray[$c] instead of resultArray[$i]; you still need resultArray[$i] to test the rest of the $c's.

          Well, well. I was trying to be a cleverdick but have found that your first suggestion is so much more elegant (creating an array of the unique values) than mine (removing the duplicates, which ended up causing problems as the index was getting screwed up). So thank you for your help.

          Regards.

          Steve.

            Write a Reply...