一、判断是否有重复值

if (count($arr) != count(array_unique($arr))) {
 echo '该数组有重复值';
}

二、获取重复的值(一维数组的值完全相等是重复;如果是二维数组,二维数组中的值必须完全相同才是重复)

function getRepeat($arr) {
    
 // 获取去掉重复数据的数组 
 $unique_arr = array_unique ( $arr ); 
 // 获取重复数据的数组 
 $repeat_arr = array_diff_assoc ( $arr, $unique_arr );
 
 return $repeat_arr;
}

三、二维数组局部键对应值数据判断是否重复

/*
    作用:根据二维数组中的部分键值判断二维数组中是否有重复值
    参数:
        $arr —— 目标数组
        $keys —— 要进行判断的键值组合的数组
    返回:重复的值
    扩展:判断的键值
*/
function getRepeat($arr,$keys) {
    $unique_arr = array();
    $repeat_arr = array();
    foreach ($arr as $k => $v) {
        $str = "";
        foreach ($keys as $a => $b) {
            $str .= "{$v[$b]},";
        }
        if( !in_array($str, $unique_arr) ){
            $unique_arr[] = $str;
        } else {
            $repeat_arr[] = $v;
        }
    }
    return $repeat_arr;
}

举个例子:

$arr1 = array("aaa","bbb","ccc","ddd","aaa","bbb");
$arr2 = array("aaa","bbb","ccc","ddd","aaa");
$arr3 = array("aaa","bbb","lll","ddd","aaa","bbb");
$arr = array($arr1,$arr2,$arr3);
 
$keys = array(0,1,2);
var_dump(getRepeat($arr,$keys));
 
输出:
 
D:\office\wamp64\www\test.php:46:
array (size=1)
 0 => 
 array (size=5)
 0 => string 'aaa' (length=3)
 1 => string 'bbb' (length=3)
 2 => string 'ccc' (length=3)
 3 => string 'ddd' (length=3)
 4 => string 'aaa' (length=3)

关注友儿不迷路

Last modification:February 19th, 2021 at 05:25 pm
如果觉得我的文章对你有用,请随意赞赏