一尘不染

获取数组中重复值的键

php

我有以下数组:

$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
)
  1. 现在如何显示具有重复值的键?在此函数不应返回([0],[9]),因为没有重复的值。
  2. 如何找到相同值的键,例如 对于“ 2011-06-25”,应返回[7],[8]

阅读 240

收藏
2020-05-29

共1个答案

一尘不染

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”作为第二个参数发送,它将返回没有重复值的原始数组。

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

2020-05-29