如何删除重复的数组? [英] How to delete duplicates in an array?

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

问题描述

我怎样才能在数组中删除重复?

How can I delete duplicates in array?

例如,如果我有以下数组:

For example if I had the following array:

$array = array('1','1','2','3');

我希望它成为

$array = array('2','3');

所以我希望它删除整个值,如果两个它被发现

so I want it to delete the whole value if two of it are found

推荐答案

根据PHP版本,这应该在PHP中的所有版本> = 4.0.6,因为它不要求需要PHP> = 5.3匿名函数:

Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:

function moreThanOne($val) {
    return $val < 2;
}


$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));

演示(更改下拉PHP版本选择版本PHP的您正在使用)

DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)

这工作,因为:


  1. array_count_values​​ 将通过数组,每个值创建一个索引,每个再次遇到它时增加它。

  2. array_filter 将采取制作的磁盘阵列,并使之通过前面定义的 moreThanOne 函数,如果返回,键/值对将被删除。

  3. array_keys 将丢弃值数组创造与价值是被定义键数组部分。最后一步给你一个结果,消除原来的阵列中存在一次以上的所有值。

  1. array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
  2. array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
  3. array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.

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

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