PHP函数array_udiff_assoc

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值