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

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

问题描述

我想从数组中检索所有重复的条目.这在 PHP 中可行吗?

I want to retrieve all duplicated entries from a array. Is this possible in PHP?

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

我想返回一个只有重复值的数组:hello".

I want to return an array with just the duplicate value: "hello".

所需的输出数组:

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

推荐答案

你需要让你的函数不区分大小写以获得你正在寻找的 "Hello" => "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);

输出为:

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

<小时>

编辑@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));

因为其中一个重复值将在 array_unique 中,然后被 array_diff 截断.

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

@RyanDay

所以看看@Srikanth 或@Bucabay 的答案,它们适用于所有情况(在 Bucabay 中寻找不区分大小写的),而不仅仅是问题中指定的测试数据.

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