多维数组差异

时间:2017-08-21 10:14:26

标签: php arrays

我需要找到多维数组之间的区别

我有这样的数组:

$arr1 = array(
        'test1' => array(   
            'XXX' => array(
                'w1'     => array('id'    =>     '5'),
                'w2'     => array('id'    =>     '2'),
                'w3'     => array('id'    =>     'g'),
           ),
            'YYY' => array(
                'w1'     => array('id'    =>     '4'),
                'w2'     => array('id'    =>     '1')
           ),
           'ZZZ' => array(
                'w1'     => array('id'    =>     '3'),
                'w2'     => array('id'    =>     '9')
           ),
           'QQQ' => array(
                'w1'     => array('id'    =>     '3'),
                'w2'     => array('id'    =>     '9')
           ),            
        ),
        'test2' => array(   
            'XXX' => array(
                'w1'     => array('id'    =>     '8'),
                'w2'     => array('id'    =>     '3')
           ),
            'YYY' => array(
                'w1'     => array('id'    =>     '15'),
                'w2'     => array('id'    =>     '1')
           ),
           'ZZZ' => array(
                'w1'     => array('id'    =>     '5'),
                'w2'     => array('id'    =>     '2')
           ),           
        ),
        );


$arr2 = array(
        'test1' => array(
           'XXX' => array(
                'w1'     => array('id'    =>     '5'),
                'w2'     => array('id'    =>     '2'),
                'w3'     => array('id'    =>     'g'),
                'w4'     => array('id'    =>     'x'),
           ),
          'YYY' => array(
                'w1'     => array('id'    =>     '4'),
                'w2'     => array('id'    =>     '1')
           ),
           'ZZZ' => array(
                'w1'     => array('id'    =>     '3'),
                'w2'     => array('id'    =>     '9')
           ),
         ),
       );    

我需要删除重复项,但我需要比较第一级键,第二级键和最后一级键,值对,所以我的结果应该是那样

array(
            'test1' => array(
               'XXX' => array(
                    'w4'     => array('id'    =>     'x'),
               ),
)

我尝试使用

function check_key($a,$b) {

if ($a===$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;    
}

function check_value($a,$b) {

if ($a===$b)
  {
  return 0;
} 
  return ($a>$b)?1:-1;
}

$merged_arr = array_udiff_uassoc($arr2,$arr1,"check_key","check_value"); 

但是这个功能不能比较最后一级的最后一级键值对。

1 个答案:

答案 0 :(得分:1)

尝试使用此功能。我认为这会对您有所帮助。

$result[] = array_diff_key($arr1, $arr2);
print_r($result);