我有以下数组:
$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 )
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”作为第二个参数发送,它将返回没有重复值的原始数组。
或者,您可以将原始数组作为参考传递,并在返回重复数组时进行相应的调整