3

How do i get the result of intersection between two Array of Objects in PHP.

For Example,

the value of $array1 is

Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [influencer_id] => 2
            [follower_id] => 1
        )

)

and the value of $array2 is,

Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [influencer_id] => 1
            [follower_id] => 2
        ),
    [1] => stdClass Object
        (
            [id] => 3
            [influencer_id] => 3
            [follower_id] => 2
        ),

)

So, what i want to get in $result is

Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [influencer_id] => 2
            [follower_id] => 1
        )

)

What is the best way to get it?

Thanks in advance!

2
  • Do you mean the object of $array2[0] has the same value of $array1[0]? If so I think there is a misstyping. Commented Jun 16, 2015 at 7:02
  • No. if any element in $array2 matches with any element with $array1 that should be in the result. note that the elements are object here. Commented Jun 16, 2015 at 7:42

2 Answers 2

5

You can do that using array_uintersect function and defining manually your callback comparison function :

$arr1 = json_decode('[{"id":2,"influencer_id":2,"follower_id":1}]');
$arr2 = json_decode('[{"id":2,"influencer_id":2,"follower_id":1},{"id":3,"influencer_id":3,"follower_id":2}]');

$arr3 = array_uintersect($arr1, $arr2, function ($e1, $e2) { 
    if($e1->id == $e2->id && $e1->influencer_id == $e2->influencer_id && $e1->follower_id == $e2->follower_id) {
        return 0;
    } else {
        return 1;
    }
});

var_dump($arr3);
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use array_intersect

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

2 Comments

It gives this error "Object of class stdClass could not be converted to string"
nah comparing objects, read this post for this stackoverflow.com/questions/2834607/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.