从数组PHP获取已删除/重复的键值

时间:2018-11-25 05:51:38

标签: php arrays multidimensional-array

首先,这不是重复的,因为我还没有找到有关此的任何信息。 我们可以使用以下从数组成功删除重复值的例子:

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

使用以下操作,我可以删除重复项(通过键):

        $MSGS_array  = array();
        foreach ($messages as $message) {
            $MSGS_array[$message['user']] = $message;
        }

但是问题是如何获得删除的用户键值?

OR

如何从上面的数组中获取所有具有键 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 ) 
 );

1 个答案:

答案 0 :(得分:1)

这是查找重复消息的一种方法。首先,我们通过检查user的值计数来找到非唯一用户。然后,通过查看$messages是否在非唯一用户数组中来过滤user中的消息:

$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);

输出:

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

Demo on 3v4l.org

更新

要仅返回user键的数组,可以将array_map应用于$duplicate_messages数组:

$duplicate_users = array_map(function ($v) { return array('user' => $v['user']); }, $duplicate_messages);

或者您可以直接从$messages$non_unique_users数组派生它:

$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);

在两种情况下,输出均为

Array ( 
    [2] => Array ( [user] => user1 ) 
    [3] => Array ( [user] => user1 ) 
)

Demo on 3v4l.org