PHP二维数组去重方法大全

1.简单的二维数组去重

function array_unique_fb($array2D=[]) {
    $temp = [];
    foreach ($array2D as $v) {
        $v = join(",", $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    $temp = array_unique($temp);//去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v) {
        $temp[$k] = explode(",", $v);//再将拆开的数组重新组装
    }
    return $temp;
}

 2.二维数组去掉重复值 保留键名

/**
 * @param  [type] $array2D [二维数组]
 * @param  [type] $keys    [全部键名]
 * @return [type]          [去重后的数组]
 */
function array_unique_fb($array2D=[], $keys=[]){
    $temp = [];
    $temp2 = [];
    foreach ($array2D as $k=>$v){  
        $v=join(',',$v);  
        $temp[$k]=$v;  
    }  
    $temp=array_unique($temp);

    foreach ($temp as $k => $v){  
        $array=explode(',',$v);
        foreach($keys as $index => $key)  
        {    
            $temp2[$k][$key] = $array[$index];  
        }  
    }  
    return $temp2;  
}

 3.二位数组按某个键判断是否重复去重

/**
 * @param  [type] $arr [description]
 * @param  [type] $key [description]
 * @return [type]      [description]
 */
function array_unset_tt($arr=[],$key=null){   
    //建立一个目标数组
    $res = array();      
    foreach ($arr as $value) {       
       //查看有没有重复项
        if(isset($res[$value[$key]])){
            unset($value[$key]);
        }else{
            $res[$value[$key]] = $value;
        }  

    }
    return $res;
}

你可能感兴趣的:(php,开发语言,后端)