首页 >后端开发 >php教程 >2000条数据的数组,找出有重复值的索引

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

WBOY
WBOY原创
2016-06-13 10:37:161030浏览

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>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn