代码之家  ›  专栏  ›  技术社区  ›  Malfist

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

  •  2
  • Malfist  · 技术社区  · 15 年前

    我有一个这样的物体:

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

    我在一个数组中最多有30个,它们是按 $userid .

    通过数组并基于以下内容删除重复对象的最佳方法是什么 美元用户ID (忽视) $date )?

    2 回复  |  直到 15 年前
        1
  •  7
  •   Peter Bailey    15 年前

    这是一个简单的测试,至少应该让你开始。您的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
  •  1
  •   cgp    15 年前
    $temp = array($fans[$x]);
    for(var $x=1;$x<sizeof($fans);$x++) {
      if ($fans[$x]->userid != $fans[$x]->userid)
         $temp[] = $fans[$x];
    }
    

    需要临时变量,但有效。