删除的quantity
的属性,如果从他们身上你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);
'unset($ stored-> quantity)' – Ahmad
'return($ key =='quantity')|| ($ stored == $ item);' – AbraCadaver