刪除的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