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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素