如何在php中比较两个阵列?
$arr1[0] = ['user_id' => 1, 'username' => 'bob'];
$arr1[1] = ['user_id' => 2, 'username' => 'tom'];
//and
$arr2[0] = ['user_id' => 2, 'username' => 'tom'];
$arr2[1] = ['user_id' => 3, 'username' => 'john'];
$arr2[2] = ['user_id' => 21, 'username' => 'taisha'];
$arr2[3] = ['user_id' => 1, 'username' => 'bob'];
我需要返回不包含加倍的数组:
$result[0] = ['user_id' => 3, 'username' => 'john'];
$result[1] = ['user_id' => 21, 'username' => 'taisha'];
我只会嵌套foreach loop
$tmpArray = array();
foreach($newData as $arr2) {
$duplicate = false;
foreach($oldData as $arr1) {
if($arr1['user_id'] === $arr2['user_id'] && $arr1['username'] === $arr2['username']) $duplicate = true;
}
if($duplicate === false) $tmpArray[] = $arr2;
}
然后,您可以将$ tmparray用作newarray
您可以使用标准功能来实现目标:
// Function that sorts element array by key and
// kinda create string representation (needed for comparing).
$sortByKeyAndSerialize = function (array $item) {
ksort($item);
return serialize($item);
};
// Map arrays to arrays of string representation and leave only unique.
$arr1 = array_unique(array_map($sortByKeyAndSerialize, $arr1));
$arr2 = array_unique(array_map($sortByKeyAndSerialize, $arr2));
// Merge two arrays together and count values
// (values become keys and the number of occurances become values).
$counts = array_count_values(array_merge($arr1, $arr2));
// Leave only elements with value of 1
// (i.e. occured only once).
$unique = array_filter($counts, function ($item) {
return $item === 1;
});
// Grab keys and unserialize them to get initial values.
$result = array_map('unserialize', array_keys($unique));
这里正在工作演示。
可以随意将此代码包装在功能或其他方面。
避免在代码中使用嵌套循环,这是一个不好的伏都教。如果可能的话,避免完全使用显式循环(例如for
,while
)。
我为您的问题做了一个功能
function compareArrays($array1,$array2)
{
$merged_array = array_merge($array1,$array2);
$trimmed_array=[];
foreach($merged_array as $array)
{
$found=false;
$index_flag;
foreach($trimmed_array as $key=>$tarr)
{
if($tarr['user_id']==$array['user_id'] && $tarr['username']==$array['username'] )
{
$found=true;
$index_flag=$key;
break;
}
}
if($found)
{
array_splice($trimmed_array, $index_flag,1);
}
else
{
array_push($trimmed_array,$array);
}
}
return $trimmed_array;
}
我对其进行了测试,并完全获得了您的结果,您可以用 -
这样的数组调用它 compareArrays($arr1,$arr2);