如果存在,PHP将从另一个中删除数组项

时间:2017-05-07 09:35:25

标签: php arrays multidimensional-array array-difference

我有2个对象数组:Array A和Array B.如何检查Array A中是否存在Array B中的对象,如果存在则从Array A中删除它。

示例:

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

删除数组A后应如下所示:

   [
       {"id": 2, "name": "item2"},
       {"id": 4, "name": "item4"}
   ]

3 个答案:

答案 0 :(得分:0)

您可以使用array_udiff,您可以参考这些帖子进行数组比较post1post2live demo

print_r(array_udiff($A, $B, function($a, $b){return $a['id'] == $b['id'] && $a['name'] == $b['name'] ? 0 : -1;}));

答案 1 :(得分:0)

我们正在使用array_map首先使用objectjson_encode转换为字符串,这会将数组转换为json string然后我们找到array_diff这两个数组都是。

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

答案 2 :(得分:0)

array_filter可能有所帮助。

$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