从MultiArray删除所有重复的键和值

时间:2018-11-26 07:11:59

标签: php arrays multidimensional-array

我想从两个阵列中完全删除重复项(不要删除重复项并删除它们的唯一所有权)。我尝试使用array_mergearray_filterarray_uniqueunseting的值。全部只是删除重复项,而不删除所有重复的键和值。

输入:

// ARRAY 1
array(
[0] => Array ( 
    [user] => user1 
    [sending_time] => 1536513874 
    [read_time] => 1536567672 
    [content] => def 
    [recipient_status] => read 
)
);

// ARRAY 2
Array ( 
[0] => Array ( 
    [user] => 2224  
    [sending_time] => 1536513903 
    [read_time] => 1536513941 
    [content] => sad 
    [recipient_status] => read 
) 
[1] => Array ( 
    [user] => 3310  
    [sending_time] => 1536513903
    [read_time] => 1536513941 
    [content] => sad 
    [recipient_status] => read 
)
[2] => Array ( 
    [user] => user1 
    [sending_time] => 1536513874 
    [read_time] => 1536567672 
    [content] => def 
    [recipient_status] => read 
)

我尝试过什么?

array_merge($array2, $array1);

使用array_merge之后,再使用:array_unique($array, SORT_REGULAR);

期望的输出是:

与上述两个数组一样,键为[user]且值为user1的子数组类似,我想删除这两个数组,因此输出应为:

array (
    [0] => 
    array (
      [user] => 2023,
      [sending_time] => 1536513903,
      [read_time] => 1536513941,
      [content] => sad,
      [recipient_status] => read,
    )
    [1] => 
    array (
      [user] => 3310,
      [sending_time] => 1536513903,
      [read_time] => 1536513941,
      [content] => sad,
      [recipient_status] => read,
    )
)

3 个答案:

答案 0 :(得分:2)

您可以结合使用array-filterarray-searcharray-column

考虑使用以下内容:

// creating example arrays
$arr1 = array(array("user" => "user1", "content" => "def"));
$a = array("user" => 2224, "content" => "aaa");
$b = array("user" => 3310, "content" => "bbb");
$c = array("user" => "user1", "content" => "ccc");
$arr2 = array($a, $b, $c);

// filter $arr2 as element that are not exist in $arr1
$arr = array_filter($arr2, function($elem) use ($arr1) {
        return (array_search($elem["user"], array_column($arr1, 'user')) === false);
});

这将仅在$arr中的第2个元素中返回$arr2

答案 1 :(得分:0)

您可以尝试遍历数组,仅将非重复项添加到另一个数组中并返回此数组。

答案 2 :(得分:0)

您想要的是array_merge_recursive()

$result = array_merge_recursive($arr2, $arr1);

资源