如何从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);
序列化和惟一的替代方案
$test = [
['abc','def'],
['ghi','jkl'],
['mno','pql'],
['abc','def'],
['ghi','jkl'],
['mno','pql'],
];
$result = array_reduce(
$test,
function($carry,$item){
if(!in_array($item,$carry)) {
array_push($carry,$item);
}
return $carry;
},
[]
);
var_dump($result);
/*
php unique.php
array(3) {
[0] =>
array(2) {
[0] =>
string(3) "abc"
[1] =>
string(3) "def"
}
[1] =>
array(2) {
[0] =>
string(3) "ghi"
[1] =>
string(3) "jkl"
}
[2] =>
array(2) {
[0] =>
string(3) "mno"
[1] =>
string(3) "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);