如何在PHP中删除对象数组中的重复项?

时间:2021-11-17 08:43:08

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.

我在一个数组中最多有30个,它们按$ userid排序。

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

通过数组的最佳方法是什么,并删除基于$ userid的重复对象(忽略$ date)?

2 个解决方案

#1


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

这是一个简单的测试,至少应该让你开始。您的__toString方法可能需要更精细,以便为您的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 ) ); ?> </pre>

#2


$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.

需要一个临时变量,但有效。

#1


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

这是一个简单的测试,至少应该让你开始。您的__toString方法可能需要更精细,以便为您的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 ) ); ?> </pre>

#2


$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.

需要一个临时变量,但有效。