对于array_diff_assoc()的PHP反转,删除重复的值

时间:2012-02-10 23:37:50

标签: php array-difference

我有权限级别系统,所以我需要从我的数组中删除我的previos选择的权限。例如:

My permissions:  read, write
All permissions: read, write, update, delete
I need return:   update, delete

问题:array_diff_assoc()比较精确键,[0] = [0],我需要比较值而不是键,并返回所有权限,没有,我的previos选择权限,而不是删除值。

res['all_withou_pre_selected_permissions'] = array_diff_assoc($all_permissions,$res['my_permissions']);
print_r($res['all_withou_pre_selected_permissions']);

我的数组并返回

My permissions
array(2) {
  [0]=>
  array(6) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(9) "Adicionar"
    [1]=>
    string(9) "Adicionar"
    ["Nome"]=>
    string(3) "kin"
    [2]=>
    string(3) "kin"
  }
  [1]=>
  array(6) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(7) "Excluir"
    [1]=>
    string(7) "Excluir"
    ["Nome"]=>
    string(3) "kin"
    [2]=>
    string(3) "kin"
  }
}

All Permissions
array(8) {
  [0]=>
  array(4) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(9) "Adicionar"
    [1]=>
    string(9) "Adicionar"
  }
  [1]=>
  array(4) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(6) "Editar"
    [1]=>
    string(6) "Editar"
  }
  [2]=>
  array(4) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(7) "Excluir"
    [1]=>
    string(7) "Excluir"
  }
  [3]=>
  array(4) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(3) "Ler"
    [1]=>
    string(3) "Ler"
  }

Return of PHP code

array(6) {
  [2]=>
  array(4) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(7) "Excluir"
    [1]=>
    string(7) "Excluir"
  }
  [3]=>
  array(4) {
    ["Modulo"]=>
    string(15) "Administradores"
    [0]=>
    string(15) "Administradores"
    ["Tipo"]=>
    string(3) "Ler"
    [1]=>
    string(3) "Ler"
  }

2 个答案:

答案 0 :(得分:1)

你有什么理由不能使用array_diff吗?

$my = array( 'read', 'write');
$all = array( 'read', 'write', 'update', 'delete');

var_dump( array_diff( $all, $my));

<强>输出:

array(2) {
  [2]=>
  string(6) "update"
  [3]=>
  string(6) "delete"
}

答案 1 :(得分:0)

两个数组的 union

$union = array_unique( array_merge( $arr1, $arr2 ) );

intersection他们:

$intersect = array_intersect( $arr1, $arr2 );

差异

$diff = array_diff( $arr1, $arr2 );

对称差异 source

$sym_diff = array_merge( array_diff( $arr1, $arr2 ), array_diff( $arr2, $arr1 ) );

另一种可能性是写一个简单的FilterIterator

由于Google SERP中没有其他问题,我在这个老问题上留下了答案。