2

I have 2 object arrays: Array A and Array B. how can I check if object from Array B exists in Array A. and if exists remove it from Array A.

Example:

Array A:
   [
       {"id": 1, "name": "item1"},
       {"id": 2, "name": "item2"},
       {"id": 3, "name": "item3"},
       {"id": 4, "name": "item4"}
   ]

Array B 
   [
       {"id": 1, "name": "item1"},
       {"id": 3, "name": "item3"}
   ]

After removing Array A should look like:

   [
       {"id": 2, "name": "item2"},
       {"id": 4, "name": "item4"}
   ]
LF00
  • 27,015
  • 29
  • 156
  • 295
blahblah
  • 1,010
  • 15
  • 40
  • You can use such trick which I see anywhere - `$ArrayA = array_map('serialize', $ArrayA); $ArrayB = array_map('serialize', $ArrayB); $ArrayA = array_diff($ArrayA, $ArrayB); $ArrayA = array_map('unserialize', $ArrayA); print_r($ArrayA);` – splash58 May 07 '17 at 10:00
  • I found answer in this [question](http://stackoverflow.com/questions/6472183/php-get-difference-of-two-arrays-of-objects) – blahblah May 07 '17 at 10:01

3 Answers3

0

You can use array_udiff, and you can refer to these post for array compare post1 and post2. live demo

print_r(array_udiff($A, $B, function($a, $b){return $a['id'] == $b['id'] && $a['name'] == $b['name'] ? 0 : -1;}));
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
0

Here we are using array_map which first convert object's to string using json_encode which will convert array to json string then we are finding array_diff for both the array's.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$array1=
[
    (object) ["id"=> 1, "name"=> "item1"],
    (object) ["id"=> 2, "name"=> "item2"],
    (object) ["id"=> 3, "name"=> "item3"],
    (object) ["id"=> 4, "name"=> "item4"]
];
$array1=array_map(function($value){return json_encode($value);}, $array1);
$array2=
[
    (object) ["id"=> 1, "name"=> "item1"],
    (object) ["id"=> 3, "name"=> "item3"]
];
$array2=array_map(function($value){return json_encode($value);}, $array2);

$result=array_map(function($value){return json_decode($value);}, array_diff($array1, $array2));
print_r($result);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

array_filter might help.

$a =  [
       ["id"=> 1, "name"=> "item1"],
       ["id"=> 2, "name"=> "item2"],
       ["id"=> 3, "name"=> "item3"],
       ["id"=> 4, "name"=> "item4"]
   ];


print_r(array_filter($a, function($e) { 
  return  !in_array($e, [["id"=> 1, "name"=> "item1"],["id"=> 3, "name"=> "item3"]]);
}));
/* =>
    Array

(
    [1] => Array
        (
            [id] => 2
            [name] => item2
        )

    [3] => Array
        (
            [id] => 4
            [name] => item4
        )

)  
 */

http://php.net/manual/en/function.array-filter.php

http://php.net/manual/ru/function.in-array.php

marmeladze
  • 6,468
  • 3
  • 24
  • 45