当前位置:Gxlcms > PHP教程 > 2000条数据的数组,找出有重复值的索引

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

时间:2021-07-01 10:21:17 帮助过:4人阅读

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);

------解决方案--------------------
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);

------解决方案--------------------
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);                     

人气教程排行