如何从PHP多维数组中删除重复值?
示例数组:
Array
(
[0] => Array
(
[0] => abc
[1] => def
)
[1] => Array
(
[0] => ghi
[1] => jkl
)
[2] => Array
(
[0] => mno
[1] => pql
)
[3] => Array
(
[0] => abc
[1] => def
)
[4] => Array
(
[0] => ghi
[1] => jkl
)
[5] => Array
(
[0] => mno
[1] => pql
)
)
对于长度不受限制的(n)维数组,尝试此解决方案
比如这个数组
$arr= [
0 => [0=>"a" , 1=>"b" , 2=>"c" ] ,
1 => [0=>"x" , 1=>"b" , 2=>"a", 3=>"p"],
2=> [
[
0=>"y" ,
1=>"b" ,
2=> [0=>"x" , 1=>"m" , 2=>"a"]
],
1=>"z" ,
2=>"v"
]
];
这就是答案
$ar2=[];
$ar3=[];
function test($arr){
global $ar2,$ar3;
if(is_array($arr)){
return array_map("test",$arr);
}
if(!isset($ar2[$arr])){
$ar2[$arr]=1;
$ar3[]=$arr;
}
}
array_map("test",$arr);
print_r($ar3);
如果"remove duplicate "的意思是"remove duplicate,但保留一个",一个解决方案可能是首先在"identifier column"上应用array_unique(…),然后在原始数组中删除所有已从列数组中删除的键:
$array = [
[
'id' => '123',
'foo' => 'aaa',
'bar' => 'bbb'
],
[
'id' => '123',
'foo' => 'ccc',
'bar' => 'ddd'
],
[
'id' => '567',
'foo' => 'eee',
'bar' => 'fff'
]
];
$ids = array_column($array, 'id');
$ids = array_unique($ids);
$array = array_filter($array, function ($key, $value) use ($ids) {
return in_array($value, array_keys($ids));
}, ARRAY_FILTER_USE_BOTH);
结果是:
Array
(
[0] => Array
(
[id] => 123
[foo] => aaa
[bar] => bbb
)
[2] => Array
(
[id] => 567
[foo] => eee
[bar] => fff
)
)