array_udiff_assoc通过使用自定义函数比较值,内建函数比较键,计算数组的差集
/**
* Computes the difference of arrays with additional index check, compares data by a callback function
* @link https://php.net/manual/en/function.array-udiff-assoc.php
* @param array $array1 <p>
* The first array.
* </p>
* @param array $array2 <p>
* The second array.
* </p>
* @param array $_ [optional]
* @param callback $data_compare_func <p>
* The callback comparison function.
* </p>
* <p>
* The user supplied callback function is used for comparison.
* It must return an integer less than, equal to, or greater than zero if
* the first argument is considered to be respectively less than, equal
* to, or greater than the second.
* </p>
* @return array array_udiff_assoc returns an array
* containing all the values from array1
* that are not present in any of the other arguments.
* Note that the keys are used in the comparison unlike
* array_diff and array_udiff.
* The comparison of arrays' data is performed by using an user-supplied
* callback. In this aspect the behaviour is opposite to the behaviour of
* array_diff_assoc which uses internal function for
* comparison.
* @meta
*/
function array_udiff_assoc(array $array1, array $array2, array $_ = null, $data_compare_func) { }
示例:注意这里使用 `===`,和 `==`区别
$array1 = [
'a' => 'aaa-1',
'b' => 0,
'c' => 'ccc'
];
$array2 = [
'a' => 'aaa-2',
'b' => '',
'e' => 'ccc'
];
$result = array_udiff_assoc($array1, $array2, function($v1, $v2){
// 注意这里使用 `===`,和 `==`区别
// if ($v1 == $v2) {
// return 0;
// }
//结果
//array(2) {
// 'a' =>
// string(5) "aaa-1"
// 'c' =>
// string(3) "ccc"
//}
// ---------------------------------------
if ($v1 === $v2) {
return 0;
}
//结果
//array(3) {
// 'a' =>
// string(5) "aaa-1"
// 'b' =>
// int(0)
// 'c' =>
// string(3) "ccc"
//}
return $v1 > $v2 ? 1 : -1;
});
var_dump($result);