【问题标题】:Compare two objects apart from one property? php比较除了一个属性之外的两个对象? php
【发布时间】:2017-08-06 11:19:48
【问题描述】:

我正在尝试比较两个对象,看看它们是否相同。在执行此操作时,我需要忽略其中一个属性。

这是我当前的代码:

$exists = array_filter($this->products, function($stored, $key) use ($item) {
    return ($stored == $item);
}, ARRAY_FILTER_USE_BOTH);

这将比较对象是否完全相同。我需要从$stored 中临时删除quantity 的属性

【问题讨论】:

  • unset($stored->quantity)
  • return ($key == 'quantity') || ($stored == $item);

标签: php object properties compare


【解决方案1】:

由于这是一个对象的数组,如果您从它们中unset 属性,它不会仅在array_filter 的上下文中取消设置属性。因为数组包含object identifiers,它实际上会从$this->products 中的对象中删除属性。如果您想暂时删除一个属性进行比较,只需在取消设置之前保存它的副本,然后进行比较,然后在返回比较结果之前将其添加回对象。

$exists = array_filter($this->products, function($stored, $key) use ($item) {
    $quantity = $stored->quantity;      // keep it here
    unset($stored->quantity);           // temporarily remove it
    $result = $stored == $item;         // compare
    $stored->quantity = $quantity;      // put it back
    return $result;                     // return
}, ARRAY_FILTER_USE_BOTH);

另一种可能性是克隆对象并从克隆中取消设置属性。根据对象的复杂程度,这可能效率不高。

$exists = array_filter($this->products, function($stored, $key) use ($item) {
    $temp = clone($stored);
    unset($temp->quantity);
    return $temp == $item;
}, ARRAY_FILTER_USE_BOTH);

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多