PHP:从关联数组中删除重复的值,并返回一个包含重复值的关联数组 [英] PHP : Remove duplicate values from associative array and return an associative array containing the duplicate values

查看:163
本文介绍了PHP:从关联数组中删除重复的值,并返回一个包含重复值的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下的关联数组

$arr = [1=>0, 2=>1, 3=>1, 4=>2]

我想从初始数组中删除重复值,并将这些重复值作为新数组返回.所以我最终会得到类似的东西;

I would like to remove the duplicate values from the initial array and return those duplicates as a new array. So I would end up with something like;

$arr = [1=>0, 4=>2]

$new_arr = [2=>1, 3=>1]

PHP是否提供了这样的功能?如果没有,我将如何实现呢?

Does PHP provide such a function or if not how would I achieve this?

推荐答案

尝试:

使用array_filter()从数组中获取所有重复值

Use array_filter() to get all duplicate values from array

使用array_diff()从数组中获取所有唯一值

Use array_diff() to get all unique values from array

$array = array(1=>0, 2=>1, 3=>1, 4=>2);
$counts = array_count_values($array);
$duplicates = array_filter($array, function ($value) use ($counts) {
    return $counts[$value] > 1;
});
print '<pre>';print_r($duplicates);

$result=array_diff($array,$duplicates);
print '<pre>';print_r($result);

输出:

Array
(
    [2] => 1
    [3] => 1
)

Array
(
    [1] => 0
    [4] => 2
)

这篇关于PHP:从关联数组中删除重复的值,并返回一个包含重复值的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆