【问题标题】:How can I remove duplicates in an object array in PHP?如何在 PHP 中删除对象数组中的重复项?
【发布时间】:2010-11-06 05:57:04
【问题描述】:

我有一个这样的对象:

class FanStruct{
    public $date; 
    public $userid;

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

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

遍历数组并根据$userid 删除重复对象的最佳方法是什么(忽略$date)?

【问题讨论】:

  • 虽然这是一个老问题,并且已经有一个很好接受的答案,但值得一提的是,您可以(并且应该)使用 SORT_REGULAR,如下所述:stackoverflow.com/a/18203564/1412157

标签: php arrays


【解决方案1】:

这是一个简单的测试,至少可以帮助您入门。您的 __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 ) );

?>

【讨论】:

  • 从 5.2.9 开始,您不再需要 __toString(),当您使用 SORT_REGULAR 时,它将基于 (object)$x == (object)$y 比较工作。
【解决方案2】:
$temp = array($fans[$x]);
for(var $x=1;$x<sizeof($fans);$x++) {
  if ($fans[$x]->userid != $fans[$x]->userid)
     $temp[] = $fans[$x];
}

需要一个临时变量,但可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 2022-12-05
    • 2012-11-24
    • 2017-09-01
    • 1970-01-01
    • 2017-05-14
    • 2014-08-24
    • 2017-06-01
    相关资源
    最近更新 更多