PHP - udiff比较多个值

时间:2015-09-01 08:55:51

标签: php arrays multidimensional-array diff array-difference

我有两个多维数组,我需要比较它们。问题是每个子阵列通过permission_idcreateview的组合是唯一的。我需要比较这些数组以检查是否存在这样一个独特的子阵列。子阵列的关键可以是不同的。到目前为止,我有这个:

$updated_permissions = array(
    0 => array(
        'create' => 0,
        'view' => 1,
        'permission_id' => "87"
    ),
    1 => array(
        'create' => 0,
        'view' => 1,
        'permission_id' => "11"
    ),
    2 => array(
        'create' => 1,
        'view' => 0,
        'permission_id' => "11"
    ),
    3 => array(
        'create' => 0,
        'view' => 1,
        'permission_id' => "18"
    )
);

$origin_permissions = array(
    0 => array(
        'create' => 0,
        'view' => 1,
        'permission_id' => "8"
    ),
    1 => array(
        'create' => 0,
        'view' => 1,
        'permission_id' => "11"
    ),
    2 => array(
        'create' => 1,
        'view' => 0,
        'permission_id' => "12"
    )
);

$arrdiff = array_merge(
    array_udiff($origin_permissions, $updated_permissions, 'udiffCompare'),
    array_udiff($updated_permissions, $origin_permissions, 'udiffCompare')
);

function udiffCompare($a, $b) {
    return $a['permission_id'] - $b['permission_id'];
}

print_r($arrdiff);

但只比较permission_id所以结果如下:

[0] => Array (
    [create] => 0
    [view] => 1
    [permission_id] => 8
    )
[1] => Array (
    [create] => 1
    [view] => 0
    [permission_id] => 12
    )
[2] => Array (
    [create] => 0
    [view] => 1
    [permission_id] => 87
    )
[3] => Array (
    [create] => 0
    [view] => 1
    [permission_id] => 18
    )

我需要比较createview是否相同。所以我想要的结果就是这个(permission_id 11有不同的createview):

[0] => Array (
    [create] => 0
    [view] => 1
    [permission_id] => 8
    )
[1] => Array (
    [create] => 1
    [view] => 0
    [permission_id] => 12
    )
[2] => Array (
    [create] => 0
    [view] => 1
    [permission_id] => 87
    )
[3] => Array (
    [create] => 0
    [view] => 1
    [permission_id] => 18
    )
[4] => Array (
    [create] => 1
    [view] => 0
    [permission_id] => 11
    )

此代码也是here

1 个答案:

答案 0 :(得分:0)

喜欢这个吗?

function udiffCompare($a, $b) {
 if ($a['permission_id'] !== $b['permission_id'] || $a['view'] !== $b['view'] || $a['create'] !== $b['create']){
  return 1;
  }
}