Reputation: 1922
First of all this is not a duplicate as i haven't found any info about this. We can successfully remove duplicate values using the following from an array for example:
$messages= 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 )
[3] => Array ( [user] => user1 [sending_time] => 1536513532 [read_time] => 1536513745 [content] => abc [recipient_status] => read )
)
Using the following i can remove the duplicates(by key):
$MSGS_array = array();
foreach ($messages as $message) {
$MSGS_array[$message['user']] = $message;
}
But the question is how can i get the removed user key value?
OR
How can i get all the duplicates having key user and their value(s) in an array from the array above?
Expected Output:
The output should only contain the removed/duplicates Like:(i just need the duplicates with they key user)
$output= Array (
[0] => Array ( [user] => user1 )
[1] => Array ( [user] => user1 )
);
OR
$output= Array (
[0] => Array ( [user] => user1 [sending_time] => 1536513874 [read_time] => 1536567672 [content] => def [recipient_status] => read )
[1] => Array ( [user] => user1 [sending_time] => 1536513532 [read_time] => 1536513745 [content] => abc [recipient_status] => read )
);
Upvotes: 2
Views: 52
Reputation: 147146
Here is one way to find the duplicate messages. First we find the non-unique users by checking the count of the values of user
. Then we filter the messages in $messages
by seeing if the user
is in the non-unique users array:
$non_unique_users = array_filter(array_count_values(array_column($messages, 'user')), function ($v) { return $v != 1; });
$duplicate_messages = array_filter($messages, function ($v) use($non_unique_users) { return array_key_exists($v['user'], $non_unique_users); });
print_r($duplicate_messages);
Output:
Array (
[2] => Array ( [user] => user1 [sending_time] => 1536513874 [read_time] => 1536567672 [content] => def [recipient_status] => read )
[3] => Array ( [user] => user1 [sending_time] => 1536513532 [read_time] => 1536513745 [content] => abc [recipient_status] => read )
)
Update
To just return an array of the user
keys, you can apply array_map
to the $duplicate_messages
array:
$duplicate_users = array_map(function ($v) { return array('user' => $v['user']); }, $duplicate_messages);
or you can derive it directly from the $messages
and $non_unique_users
arrays:
$duplicate_users = array_map(function ($v) use($non_unique_users) { if (array_key_exists($v['user'], $non_unique_users)) return array('user' => $v['user']); }, $duplicate_messages);
In both cases the output is
Array (
[2] => Array ( [user] => user1 )
[3] => Array ( [user] => user1 )
)
Upvotes: 2