获取重复值的键数组 [英] Get the keys for duplicate values in an array
本文介绍了获取重复值的键数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我阵列是
阵列([0] => 2011-06-21 [1] => 2011-06-22 [2] => 2011-06-22 [3] => 2011-06-23 [4] =>
2011-06-23 [5] => 2011-06-24 [6] => 2011-06-24 [7] => 2011-06-25 [8] => 2011-06-25 [9]
= GT; 2011-06-26 [10] => 2011-06-26 [11] => 2011-06-27 [12] => 2011-06-27 [13] => 2011-06-
28 [14] => 2011-06-29 [15] => 2011-06-29 [16] => 2011-06-30 [17] => 2011-06-30 [18] =>
2011-07-01 [19] => 2011-07-01 [20] => 2011-07-02 [21] => 2011-07-02 [22] => 2011-07-03
[23] => 2011-07-03 [24] => 2011-07-04 [25] => 2011-07-04 [26] => 2011-07-05 [27] => 2011-
07-05 [28] => 2011-07-06 [29] => 2011-07-06 [30] => 2011-07-07 [31] => 2011-07-07)
- 现在,我怎么能显示与重复值的钥匙?
例如。在这里,函数不应返回([0],[13]),因为存在与价值没有重复。 - 如何找到该值的键,例如2011-06-29,它应该返回[15],[16]
解决方案
函数get_keys_for_duplicate_values($ my_arr,$干净= FALSE) {
如果($干净){
返回array_unique($ my_arr);
} $的DUP = $ new_arr =阵列();
的foreach($ my_arr为$关键=> $ VAL){
如果(!使用isset($ new_arr [$ VAL)){
$ new_arr [$ VAL] = $键;
}其他{
如果(使用isset($的DUP [$ VAL)){
$的DUP [$ VAL] [] = $键;
}其他{
$的DUP [$ VAL] =阵列($键);
}
}
}
返回$ DUP的;
}
显然函数名字有点长;)
现在$的DUP将包含重复的值键入一个多维数组,包含这是一个重复的每一个关键,如果你发送真作为你的第二个参数,它将返回原始数组没有重复的值。
另外,你可以传递原始数组作为参考,而返回它会相应调整您的重复阵列
if my arrays is
Array ( [0] => 2011-06-21 [1] => 2011-06-22 [2] => 2011-06-22 [3] => 2011-06-23 [4] =>
2011-06-23 [5] => 2011-06-24 [6] => 2011-06-24 [7] => 2011-06-25 [8] => 2011-06-25 [9]
=> 2011-06-26 [10] => 2011-06-26 [11] => 2011-06-27 [12] => 2011-06-27 [13] => 2011-06-
28 [14] => 2011-06-29 [15] => 2011-06-29 [16] => 2011-06-30 [17] => 2011-06-30 [18] =>
2011-07-01 [19] => 2011-07-01 [20] => 2011-07-02 [21] => 2011-07-02 [22] => 2011-07-03
[23] => 2011-07-03 [24] => 2011-07-04 [25] => 2011-07-04 [26] => 2011-07-05 [27] => 2011-
07-05 [28] => 2011-07-06 [29] => 2011-07-06 [30] => 2011-07-07 [31] => 2011-07-07 )
- Now how can I display the keys with duplicate values? eg. Here the function should NOT return ([0],[13]) since there are no duplicates with the values.
- How to find the key for the value , eg."2011-06-29" it should return [15],[16]
解决方案
function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}
$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
}
}
}
return $dups;
}
obviously the function name is a bit long;)
Now $dups will contain a multidimensional array keyed by the duplicate value, containing each key that was a duplicate, and if you send "true" as your second argument it will return the original array without the duplicate values.
Alternately you could pass the original array as a reference and it would adjust it accordingly while returning your duplicate array
这篇关于获取重复值的键数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文