如何从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
)
)
从5.2.9开始,如果你像这样使用SORT_REGULAR标志,你可以使用array_unique():
array_unique($array, SORT_REGULAR);
这使得函数比较元素是否相等,就像使用了$a == $b一样,这非常适合您的情况。
输出
Array
(
[0] => Array
(
[0] => abc
[1] => def
)
[1] => Array
(
[0] => ghi
[1] => jkl
)
[2] => Array
(
[0] => mno
[1] => pql
)
)
但是请记住,文档声明:
Array_unique()并不用于多维数组。
对此,array_unique()文档上的用户注释提供了许多解决方案。这是其中之一:
kenrbnsn at rbnsn dot com
27-Sep-2005 12:09
Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.
This function uses the serialize, array_unique, and unserialize functions to do the work.
function multi_unique($array) {
foreach ($array as $k=>$na)
$new[$k] = serialize($na);
$uniq = array_unique($new);
foreach($uniq as $k=>$ser)
$new1[$k] = unserialize($ser);
return ($new1);
}
这来自http://ca3.php.net/manual/en/function.array-unique.php#57202。
唯一一个多维数组的简单而合理的方法如下:
如果你有一个这样的数组:
Array
(
[Key1] => Array
(
[0] => Value1
[1] => Value2
[2] => Value1
[3] => Value3
[4] => Value1
)
[Key2] => Array
(
[0] => Value1
[1] => Value2
[2] => Value1
[3] => Value3
[4] => Value4
)
)
使用foreach来解决这个问题:
foreach($array as $k=>$v){
$unique=array_unique($v);
$array[$k]=$unique;
}
它会给你以下结果:
Array
(
[Key1] => Array
(
[0] => Value1
[1] => Value2
[3] => Value3
)
[Key2] => Array
(
[0] => Value1
[1] => Value2
[3] => Value3
[4] => Value4
)
)
如果你想重新排列键的顺序,
foreach($array as $k=>$v){
$unique= array_values(array_unique($v));
$array[$k]=$unique;
}
这个操作会给你这样排列的键值:
Array
(
[Key1] => Array
(
[0] => Value1
[1] => Value2
[2] => Value3
)
[Key2] => Array
(
[0] => Value1
[1] => Value2
[2] => Value3
[3] => Value4
)
)
我希望这能澄清一切。