简体   繁体   中英

The result of 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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM