Home  >  Article  >  Backend Development  >  2000条数据的数组,找出有重复值的索引

2000条数据的数组,找出有重复值的索引

WBOY
WBOYOriginal
2016-06-13 13:20:26801browse

2000条数据的数组,找到有重复值的索引.
例如 一个数组含有 1,2,2,2,3,4,5,5,5,6,2,2,7,8,2,5,3,9,...............

得到 2的重复索引2,3,10,11,14
  5的重复索引7,8,15
  ....

不能2重for或者while循环,这样代价太大.

------解决方案--------------------

PHP code

$arr    = array(1,2,2,2,3,4,5,5,5,6,2,2,7,8,2,5,3,9);
$tmp    = array();

foreach($arr AS $k => $v)
{
    if(isset($tmp[$v]))
    {
        if($tmp[$v])
        {
            $tmp[$v]    .= ",";
        }
        $tmp[$v]    .= $k;
    }
    else
    {
        $tmp[$v]    = "";
    }
}
foreach($tmp AS $k => $v)
{
    if($v)
    {
        echo    $k, "=>", $v, "\n";
    }
}
unset($tmp);
<br><font color="#e78608">------解决方案--------------------</font><br>
PHP code
$a = array( 1,2,2,2,3,4,5,5,5,6,2,2,7,8,2,5,3,9);
$r = array();
foreach($a as $v) {
  if(isset($r[$v])) continue;
  if($t = array_keys(array_intersect($a, array($v)))) {
    unset($t[0]);
    $r[$v] = join(',', $t);
  }
}
$r = array_diff($r, array(''));
print_r($r);
<br><font color="#e78608">------解决方案--------------------</font><br>
PHP code

$arr = array(1,2,2,2,3,4,5,5,5,6,2,2,7,8,2,5,3,9);
$str = implode(',', $arr);
foreach ($arr as $k=>$v)
{
    $t[$v] .= !isset($t[$v]) ? '' : $k . ',';
    $l += strlen($v);
    if((strrpos($str, $v.'')) == $l-strlen($v))
        $t[$v] = trim($t[$v], ',');
    ++$l;
}
print_r($t); <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn