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

Find removed and added items of modified array

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

$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 的数组,用户对列表进行了一些修改,并 post 向服务器发送了一个新数组,我想知道从第一个数组中删除了哪些项目以及哪些项目是新的!

谢谢

你可以简单地找到那些使用 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

根据 php.net 文档:

array_diff — Computes the difference of arrays

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

php.function.array-diff

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

使用 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] => 蓝色);