MR_AMDEV
MR_AMDEV

Reputation: 1922

Delete All Duplicate keys and values from MultiArray

I want to Delete duplicates completely(NOT REMOVING DUPLICATES AND GETTING UNIQUE RATHER DELETING THEM ALL) from two arrays. I have tried using array_merge, array_filter, array_unique and unseting the values. All just remove duplicates but does not delete all the duplicate keys and values.

Input:

// 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 
)

)

WHAT I HAVE TRIED?

array_merge($array2, $array1);

After using array_merge then using : array_unique($array, SORT_REGULAR);

THE EXPECTED OUTPUT IS:

As in the above two arrays ,the sub-array with key [user] having value user1 is similar I want to delete both of these so the output should be:

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,
    )
)

Upvotes: 0

Views: 92

Answers (3)

dWinder
dWinder

Reputation: 11642

You can use combination of array-filter, array-search and array-column:

Consider use the following:

// 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);
});

This will return in $arr only the ither 2 elements in $arr2

Upvotes: 2

Peter
Peter

Reputation: 9113

What you want is array_merge_recursive()

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

Resources

Upvotes: 0

Jnt0r
Jnt0r

Reputation: 173

You could try to loop through the arrays and only add nondublicates to another array and return this array.

Upvotes: 0

Related Questions