Home  >  Article  >  Backend Development  >  How to remove duplicates from php two-dimensional array? (code example)

How to remove duplicates from php two-dimensional array? (code example)

青灯夜游
青灯夜游forward
2018-11-22 14:27:393432browse

The content of this article is to introduce how to remove duplicates from two-dimensional arrays in PHP? (Code example), let everyone understand the method of deduplicating two-dimensional arrays. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface: PHP one-dimensional array deduplication is very simple, just array_unique($arr), but how to deduplicate a two-dimensional array?

Let’s take a look at the method of deduplicating two-dimensional arrays through a simple code example:

Code example:

/*
 * 二维数组去重
 * 注意:二维数组中的元素个数必须一致,且键值也得一致,否则无意义
 * @param array $arr
 * @return array $arr_after
 */
public function array_unique_2DArr($arr=array()){
    if(empty($arr) || !is_array($arr)){
        return array();
    }
    /*******处理二维数组个数不一致问题  start 其他项目用可以去掉*******/
    //判断数组中二维数组是否包含uniqueId,存在的话需要处理其他的日志信息,全部加上uniqueId,且uniqueId值必须相同
    $hasUniqueId = false;
    foreach($arr as $val){
        if(array_key_exists('uniqueId', $val)){
            $hasUniqueId = true;
            break;
        }
    }
    //如果$arr中的二维数组中uniqueId存在,则其他也增加
    if($hasUniqueId){
        foreach($arr as $_k=>$_val){
            if(!array_key_exists('uniqueId', $_val)){
                //在$_val中增加unique,只是为了和其他的带有uniqueId键值的数组元素个数保持一致       
                $_val_keys = array_keys($_val);
                $_val_vals = array_values($_val);
                array_unshift($_val_keys, 'uniqueId');
                array_unshift($_val_vals, '0_0');
                $arr[$_k] = array_combine($_val_keys, $_val_vals);
            }
        }
    }
    /********处理二维数组个数不一致问题  end********/
    foreach($arr[0] as $k => $v){  
        $arr_inner_key[]= $k;   //先把二维数组中的内层数组的键值记录在在一维数组中  
    }
    foreach ($arr as $k => $v){  
        $v =join("^",$v);   //降维 用implode()也行 ,注意,拆分时不能用逗号,用其他的不常用符号,逗号可能会由于数据本身含有逗号导致失败
        $temp[$k] =$v;      //保留原来的键值  
    }
    $temp =array_unique($temp);    //去重:去掉重复的字符串
    foreach ($temp as $k => $v){  
        $a = explode("^",$v);   //拆分后的重组 
        $arr_after[$k]= array_combine($arr_inner_key,$a);  //将原来的键与值重新合并  
    }
    return $arr_after;  
}

Summary: The above is all of this article Content, I hope it will be helpful to everyone's study. More related video tutorial recommendations: php tutorial!

The above is the detailed content of How to remove duplicates from php two-dimensional array? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete