duandian4501
duandian4501
2014-06-19 11:52

如何获得两个数组之间的差异,比如diff(添加,删除)?

已采纳

I have two snapshots of data, in arrays, such as this:

Array number 1:

array{
    'foo' => 'foo_value',
    'bar' => 'bar_value',
    'baz' => 'baz_value'
}

Array number 2:

array{
    'foo' => 'foo_value_new',
    'bar' => 'bar_value',
    'baz' => 'baz_value',
    'xyz' => 'added_value'
}

I want to get two arrays, one with added elements, one with deleted ones:

Array with added new data:

array{
    'foo' => 'foo_value_new',
    'xyz' => 'added_value'
}

Array with deleted data:

array{
    'foo' => 'foo_value',
}

How could this be archieved in php? Do any array_* functions have similar behaviour?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongpo2340 dongpo2340 7年前

    I think there is not any inbuilt function to return two array try a simple way

     $str = array(
        'foo' => 'foo_value',
        'bar' => 'bar_value',
        'baz' => 'baz_value'
    );
    $str1=array(
        'foo' => 'foo_value_new',
        'bar' => 'bar_value',
        'baz' => 'baz_value',
        'xyz' => 'added_value'
    );
    $add= array_merge(array_diff($str, $str1), array_diff($str1, $str));
    print_r($add);//Array ( [foo] => foo_value_new [xyz] => added_value )
    
    $del = array_diff($str, $str1);
    print_r($del); //Array ( [foo] => foo_value ) 
    
    点赞 评论 复制链接分享

相关推荐