【问题标题】:The result of array_uniquearray_unique 的结果
【发布时间】:2013-11-27 05:08:41
【问题描述】:

在项目中使用 DateTime 再次遇到复制问题,如果使用 array_unique 到具有对象元素的数组,(但仅使用 DateTime 有问题),请参阅代码:

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));

预计有 1 个带有 dateObj 的元素 但实际上有 2

【问题讨论】:

标签: php arrays date datetime


【解决方案1】:

函数array_unique() 将比较字符串,因此对象将被转换为字符串。解决方案是使用 __toString() 魔术方法返回完整日期标识符:

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.

【讨论】:

  • ehh,但是你创建 3 个对象的区别,但我试图找到我的问题的原因,我的项目,我不能只创建像你的例子中这样的对象
  • 我发现这是某种错误,并且有问题要查找原因
  • @sergio:是的,你的例子表现得很奇怪,它应该会抛出某种错误,或者注意,因为如果你将 $dateObj$std 转换为字符串,它会抛出 Catchable fatal error: Object of class CLASSNAME could not be converted to string ,但是当你在函数array_unique()中使用它们时,执行内部转换为字符串,没有错误出现并且输出很奇怪......
  • 嗯,这就是为什么我阅读了很多 php 文档但没有找到答案的原因..
  • @sergio:不过,array_unique() 可以处理字符串。 Two elements are considered equal if and only if (string)$elem1===(string)$elem2. In words: when the string representation is the same. The first element will be used.您正在将对象转换为字符串,没有 toString 魔术方法,所以这是个大错误。
【解决方案2】:

我还是不明白。设置数组:

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

返回:

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]

这样,array_unique 似乎可以工作...

【讨论】:

  • 呃,有些奇怪的行为
  • 就像我说的,如果对象不能转换为字符串,你就不能使用函数array_unique();结果将是不可预测的。 See demo.
  • 好吧好吧,我只是在调查。在我看来,魔法 __toString() 也不起作用。
  • @ilpaijin:你能做一个eval.in __toString() 不起作用的例子吗?似乎很难相信它不会起作用。
  • @ilpaijin:从array_unique() 函数中删除第二个参数SORT_REGULARDemo.
猜你喜欢
  • 2017-03-09
  • 1970-01-01
  • 2021-02-25
  • 2011-06-07
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多