PHP多维数组删除重复 [英] php multi-dimensional array remove duplicate

查看:204
本文介绍了PHP多维数组删除重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道这问题是需要去除重复,但我无法在别处找到答案,所以我会在要求一展身手。

Not sure if this question is a duplicate in need of removal, but I couldn't find the answer elsewhere so I'll have a go at asking.

我有一个二维数组,如下所示:

I've got a 2d array that looks as follows:

Array
(
[0] => Array
    (
        [0] => dave
        [1] => jones
        [2] => c@b.c
    )

[1] => Array
    (
        [0] => john
        [1] => jones
        [2] => a@b.c

    )

[2] => Array
    (
        [0] => bruce
        [1] => finkle
        [2] => c@b.c
    )
)

我想删除那些重复的电子邮件。所以在上面的例子中,我想只是删除为[] [0]或[] [2]。我不担心对名称或类似的东西检查,我只需要基于单个值进行重复数据删除。子阵列

I'd like to remove those with duplicate emails. So in the above example I'd like to just remove either [][0] or [][2]. I'm not worried about checking against names or anything like that, I just need the sub arrays to be deduplicated based on a single value.

目前,我有这样的事情

  if(is_array($array) && count($array)>0){
  foreach ($array as $subarray) {
    $duplicateEmail[$subarray[2]] = isset($duplicateEmail[$subarray[2]]);
    unset($duplicateEmail[$subarray[2]]);
   }
  }

但它只是是不正确的。任何帮助AP preciated。

but it just ain't right. Any help appreciated.

推荐答案

它使用数组索引的唯一一个快速的解决方案:

A quick solution which uses the uniqueness of array indexes:

$newArr = array();
foreach ($array as $val) {
    $newArr[$val[2]] = $val;    
}
$array = array_values($newArr);

注意1:从上面为可见,提供电子邮件地址的最后一场比赛是用来代替第一。这可以通过用替换的第二行被改变

Notice 1: As visible from above, the last match for an email address is used instead of the first. This can be changed by replacing the second line with

foreach (array_reverse($array) as $val) {

注意2:结果数组中的索引有所混淆。但我想这并不重要......

Notice 2: The indexes in the resulting array are somewhat mixed up. But I guess this doesn't matter...

这篇关于PHP多维数组删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆