PHP remove array items from another if exists [duplicate]

此生再无相见时 提交于 2020-01-04 05:41:13

问题


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



来源:https://stackoverflow.com/questions/43829968/php-remove-array-items-from-another-if-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!