dongyirong3564
dongyirong3564
2013-11-14 09:04
浏览 60
已采纳

array_unique的结果

Working with DateTime in projects again have a problem with duplicating if use array_unique to array which have a elemts of object,(but probles only with DateTime), see code:

class simpleClass
{
    public $dt;

    function __construct($dt)
    {
        $this->dt = $dt;
    }
}

$dateObj = new simpleClass(new DateTime);
$std = new stdClass;
$arr = [$dateObj, $dateObj, $std, $std, $std, $std];

var_dump(array_unique($arr, SORT_REGULAR));

Expected 1 element with dateObj But actually there 2

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglu5612
    donglu5612 2013-11-14 09:24
    已采纳

    Function array_unique() will compare strings, so objects will be casted to strings. Solution to that would be to use __toString() magic method to return full date identifier:

    class simpleClass
    {
        public $dt;
    
        function __construct(DateTime $dt) {
            $this->dt = $dt;
        }
    
        public function __toString() {
            return $this->dt->format('r');
        }
    
    }
    
    $dateObj1 = new simpleClass(new DateTime);
    $dateObj2 = new simpleClass(new DateTime);
    $dateObj3 = new simpleClass(new DateTime('today'));
    $arr = [$dateObj1, $dateObj2, $dateObj3];
    
    print_r(array_unique($arr));
    

    Demo.

    点赞 评论
  • duangouhui0446
    duangouhui0446 2013-11-14 13:40

    I still can't understand. Setting the array with:

    $arr = [$dateObj, $dateObj, $std, $std];
    

    returns:

    array (size=2)
        0 => 
            object(simpleClass)[1]
                public 'dt' => 
                  object(DateTime)[2]
                      public 'date' => string '2013-11-14 14:37:08' (length=19)
                      public 'timezone_type' => int 3
                      public 'timezone' => string 'Europe/Rome' (length=11)
        2 => 
           object(stdClass)[3]
    

    This way, array_unique seems to work...

    点赞 评论

相关推荐