查找已删除和添加的已修改数组的项目

时间:2017-10-22 08:36:00

标签: php arrays diff

如何查找从上一个状态数组列表中删除的项目以及添加到新项目的项目? 我的阵列:

$arrayOld = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
$arrayNew = ["Z", "B", "C", "D", "E", "F", "G", "H", "I", "J", "Y"];

说明: 我有一个名为$arrayOld的数组,用户对列表进行一些修改并将新数组发布到服务器,我想知道从第一个数组中删除了哪些项目以及哪些项目是新的!

由于

3 个答案:

答案 0 :(得分:0)

您可以使用array_diff找到那些:

$arrayOld = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
$arrayNew = ["Z", "B", "C", "D", "E", "F", "G", "H", "I", "J", "Y"];

$removes = array_diff($arrOld, $arrNew);
print_r($removes); // A , K

$adds = array_diff($arrNew,$arrOld);
print_r($adds); // Z , Y

Az php.net docs:

  

array_diff - 计算数组的差异

     

将array1与一个或多个其他数组进行比较,并返回array1中任何其他数组中不存在的值。

php.function.array-diff

答案 1 :(得分:0)

array_diff将是一个解决方案,

获取添加,

 $new_elements = array_diff($arrayNew, $arrayOld);
    print_r($new_elements); // first parameter should be new array 
and second one should be old

获取删除,

    $old_elements = array_diff($arrayOld, $arrayNew);
    print_r($old_elements); // Here first parameter should be old array 
and second one should be new

答案 2 :(得分:0)

使用diff函数,它将显示与变更项目索引的所有不同

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");


$result=array_diff($a1,$a2,$a3);
print_r($result);

结果将是:

数组([b] =>绿色[c] =>蓝色);