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

查看:27
本文介绍了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]]);
   }
  }

但这是不对的.任何帮助表示赞赏.

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天全站免登陆