Comparing 2 objects PHP

前端 未结 1 1925
我寻月下人不归
我寻月下人不归 2021-01-20 01:40

i need to compare 2 objects to remove duplicates / find new enteries.

The objects are not identical, but they contain the same username key

Here is the layou

相关标签:
1条回答
  • 2021-01-20 01:47

    No, there is no cleaner way, you have to loop over the properties. If that are not StdClass objects, I would add a custom compare method to their class:

    class Person {
    
       protected $id;
       protected $name;
       protected $age;
    
       /**
        * Compares two persons an returns true if their name
        * and age equals.
        */
       public function equals(Person $b) {
           if($b->name === $this->name && $b->age === $this->age) {
               return TRUE;
           }
           return FALSE;
       }
    }
    

    Then use it like this:

    $personA = DB::getPersonById(1);
    $personB = DB::getPersonById(2);
    
    if($personA->equals($personB)) {
        echo "They are equal";
    }
    

    However, beside from this, why not just removing the duplicates using SQL or even better use unique keys in the DB to avoid duplicates at all?

    0 讨论(0)
提交回复
热议问题