PHP remove array items from another if exists [dup

2019-07-14 23:58发布

问题:

This question already has an answer here:

  • PHP get difference of two arrays of objects 3 answers

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"}
   ]

回答1:

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;}));


回答2:

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);


回答3:

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