获取数组中重复值的键 [英] Get the keys for duplicate values in an array
本文介绍了获取数组中重复值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我的数组是
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 )
- 用重复的值显示键?
例如这里的函数不应该返回([0],[13]),因为没有重复的值。 - 如何找到该值的键,例如2011-06 -29应该返回[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);
// Comment out the previous line, and uncomment the following line to
// include the initial key in the dups array.
// $dups[$val] = array($new_arr[$val], $key);
}
}
}
return $dups;
}
显然功能名称有点长;)
obviously the function name is a bit long;)
现在,$ dups将包含由重复值键入的多维数组,其中包含每个重复的键,如果发送true作为第二个参数,它将返回原始数组,而不返回重复的值。
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屋!
查看全文