PHP从数组中仅返回重复条目 [英] php return only duplicated entries from an array

查看:97
本文介绍了PHP从数组中仅返回重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找回从阵列中的所有重复的条目,它怎么可能在PHP。

 阵列(1 =>'1233',2 =>'12334',3 =>'你好',4 =>'你好',5 => 'U');

我要回有你好数组

出认沽阵列

 阵列(1 =>'你好',2 =>'你好');


解决方案

您将需要使你的功能不区分大小写获得你好=>你好的结果,你所寻找的,试试这个方法:

  $ ARR =阵列(1 =>'1233',2 =>'12334',3 =>'你好',4 =>'你好',5- = GT;'U');//每次转换价值为大写,并删除重复值
$ withoutDuplicates = array_unique(array_map(strtoupper,$ ARR));//在$ withoutDuplicates阵列原始数组中的差,和
//将是重复的值
$ =重复和array_diff($改编,$ withoutDuplicates);
的print_r($两份);

输出是:

 阵列

[3] =>你好
[4] =>你好


按@AlixAxel编辑:

这答案是非常误导的。它只能在这个特定的条件。这个反例:

  $ ARR =阵列(1 =>'1233',2 =>'12334',3 =>'你好',4 =>'HELLO',5- = GT;'U');

失败草草收场 。此外,这是不保留重复的方式

 和array_diff($ ARR,array_unique($ ARR));

由于重复值中的一个会在 array_unique ,然后通过和array_diff 剁掉。

按@RyanDay编辑:

所以看@ SRIKANTH的或@ Bucabay的回答,这工作所有的情况下(寻找案件Bucabay的不敏感),而不仅仅是在问题规定的试验数据。

i want to retrieve all duplicated entries from a array, how can it be possible in php.

array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');

i want to return an array having hello

out put array

array(1 =>'Hello' ,2=>'hello');

解决方案

You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method:

$arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');

// Convert every value to uppercase, and remove duplicate values
$withoutDuplicates = array_unique(array_map("strtoupper", $arr));

// The difference in the original array, and the $withoutDuplicates array
// will be the duplicate values
$duplicates = array_diff($arr, $withoutDuplicates);
print_r($duplicates);

Output is:

Array
(
[3] => Hello
[4] => hello
)


Edit by @AlixAxel:

This answer is very misleading. It only works in this specific condition. This counter-example:

$arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U');

Fails miserably. Also, this is not the way to keep duplicates:

array_diff($arr, array_unique($arr));

Since one of the duplicated values will be in array_unique, and then chopped off by array_diff.

Edit by @RyanDay:

So look at @Srikanth's or @Bucabay's answer, which work for all cases (look for case insensitive in Bucabay's), not just the test data specified in the question.

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

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