0

I have two array of objects:

Array1:
[[0] => stdClass, [1] => stdClass, [2] => stdClass]
Array2
[[0] => stdClass, [1] => stdClass

I want to get the difference between two arrays (Array1-Array2).

Does it exist a better way instead of iterating the two arrays and checking the properties of the objects? Thanks a lot

C86
  • 1
  • 1

1 Answers1

0

You can use classical array_diff, but need to process strings, not objects in arrays that are compared.

So you can map these arrays to JSON strings and them revert this transformation

<?php

$a = [(object)array('a' => 'b'), (object)array('c' => 'd'), (object)array('e' => 'f')];
$b = [(object)array('a' => 'b'), (object)array('g' => 'h')];

var_dump(array_map('json_decode', array_diff(array_map('json_encode', $a), array_map('json_encode', $b))));

This code will print:

array(2) {
  [1]=>
  object(stdClass)#6 (1) {
    ["c"]=>
    string(1) "d"
  }
  [2]=>
  object(stdClass)#7 (1) {
    ["e"]=>
    string(1) "f"
  }
}

So these are elements that exist in $a and absent in $b.

A similar problem is considered under the link:

array_diff() with multidimensional arrays

Daniel
  • 7,684
  • 7
  • 52
  • 76