array intersect for object array php

前端 未结 8 1546
独厮守ぢ
独厮守ぢ 2021-01-04 05:55

I want to know how to array_intersect for object array.

8条回答
  •  庸人自扰
    2021-01-04 06:07

    Had a similar problem a few days ago, while these are answers are on the right path; I used them to work out the following:

    From Artefacto's answer return $obj1 == $obj2 didn't really work, so I wrote a simple comparative function (basically gets the md5 of the serialised object and compares that):

    function object_compare($obj1, $obj2){
      $md5 = function($obj){
        return md5(serialize($obj));
      };
      return strcmp($md5($obj1), $md5($obj2));
    }
    

    Then it’s jut a matter of calling array_uintersect with our comparative function to get the intersection:

    # $array1 / $array2 are the array of objects we want to compare
    return array_uintersect($array1, $array2, 'object_compare');
    

    In my case, I had an unknown / dynamic array of objects, so I took it a step further so I don't have to declare array_uintersect($array1, $array2, ...) specifically - but just be able to pass in an array of arrays (of objects):

    # $multiarray_of_objects is our array of arrays
    $multiarray_of_objects[] = 'object_compare';
    return call_user_func_array('array_uintersect', $multiarray_of_objects);
    

    Just gotta remember to pass in the reference to our callback / comparative function as the last string in the array. Works like a charm!

提交回复
热议问题