php – 获取数组中重复值的键

前端之家收集整理的这篇文章主要介绍了php – 获取数组中重复值的键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我的数组是
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;
}

显然功能名称有点长;)

现在$dups将包含由重复值键入的多维数组,其中包含每个重复的键,如果发送“true”作为第二个参数,它将返回原始数组而不重复的值.

或者,您可以将原始数组作为参考传递,并在返回重复数组时相应调整它

原文链接:https://www.f2er.com/php/132657.html

猜你在找的PHP相关文章