PHP

二维数组的去重

Posted by Nathan on 2017-11-07

php中常用的去重函数array_unique很好用,遗憾的是不能处理二维的数组。实际开发中,遇到此类问题,考虑的办法去二维数组降维,然后去重复,然后恢复二维。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function unique($data = array()){
$tmp = array();
foreach($data as $key => $value){
//把一维数组键值与键名组合
foreach($value as $key1 => $value1){
$value[$key1] = $key1 . '|' . $value1;//|分隔符复杂点以免冲突
}
$tmp[$key] = implode(',|,', $value);//,|,分隔符复杂点以免冲突
}
//对降维后的数组去重复处理
$tmp = array_unique($tmp);
//重组二维数组
$newArr = array();
foreach($tmp as $k => $tmp_v){
$tmp_v2 = explode(',|,', $tmp_v);
foreach($tmp_v2 as $k2 => $v2){
$v2 = explode('|', $v2);
$tmp_v3[$v2[0]] = $v2[1];
}
$newArr[$k] = $tmp_v3;
}
return $newArr;
}