douqiang5163 2017-03-15 15:44
浏览 51

除了一个属性,比较两个对象? PHP

I am trying to compare two objects, to see if they are the same. While doing this, I need to ignore one of the properties.

This is my current code:

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

This will compare the objects are the same completely. I need to temporarily remove a property of quantity from $stored

  • 写回答

1条回答 默认 最新

  • douju7765 2017-03-15 15:59
    关注

    Since this is an array of objects, if you unset properties from them, it will not unset the properties only in the context of array_filter. Because the array contains object identifiers, it will actually remove the properties from the objects in $this->products. If you want to temporarily remove a property for comparison, just save a copy of it before unsetting, then do your comparison, then add it back to the object before return the result of the comparison.

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

    Another possibility is to clone the object and unset the property from the clone. Depending on how complex the object is, this may not be as efficient.

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

报告相同问题?