2017-03-15 88 views
0

我想比較兩個對象,看看它們是否相同。在做這件事時,我需要忽略其中一個屬性。將兩個對象與一個屬性區分開來嗎? php

這是我當前的代碼:

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

這將比較對象是完全一樣。我需要因爲這是對象的數組暫時$stored

+0

'unset($ stored-> quantity)' – Ahmad

+1

'return($ key =='quantity')|| ($ stored == $ item);' – AbraCadaver

回答

0

刪除的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); 
相關問題