获取数组中重复值的键 [英] Get the keys for duplicate values in an array
本文介绍了获取数组中重复值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数组:
$myarray = Array("2011-06-21", "2011-06-22", "2011-06-22", "2011-06-23", "2011-06-23", "2011-06-24", "2011-06-24", "2011-06-25", "2011-06-25", "2011-06-26");
var_dump($myarray);
结果:
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
)
- 现在如何显示具有重复值的键?此处函数不应返回 ([0],[9]),因为这些值没有重复项.
- 如何找到相同值的键,例如.对于2011-06-25",它应该返回 [7],[8]
推荐答案
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;
}
显然函数名有点长;)
现在 $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屋!
查看全文