【问题标题】:Removing duplicate entries in an array- Undefined offset error(PHP)删除数组中的重复条目 - 未定义的偏移错误(PHP)
【发布时间】:2016-06-01 20:31:28
【问题描述】:

我是 PHP 新手,正在尝试删除数组中的重复条目。我最终得到了我想要的输出,但在此过程中我也遇到了两个“未定义的偏移”错误。这是我的代码: $this->master 指的是在类的开头声明的数组。

    public function removeDuplicates(){
        $var = count($this->master);
            for($i = 0; $i < $var; $i++){
                    for($j = 0; $j <$var; $j++){
                        if(($this->master[$i] == $this->master[$j]) && $i != $j){                           
                            $this->shiftLeft($j, $var);
                            $var --;
                        }
                    }
            }
    }

    public function shiftLeft($t, $s){
        while($t < $s){
            echo "$t ";
            $this->master[$t] = $this->master[$t+1];
            $t++;
        }
        unset($this->master[$t-1]);
    }

这可能是一个非常简单的逻辑错误,但我似乎找不到在哪里。非常感谢任何帮助。

【问题讨论】:

标签: php arrays duplicates undefined offset


【解决方案1】:

看看有没有用

 $unique = array_unique($this->master);

【讨论】:

  • 这给了我一个重复条目的数组,没有任何非重复项。如果给我一个只有一个重复实例的数组,我怎么能拥有?所以如果数组是 (a,b,a,c) 新数组会是 (a,b,c)? @andreas
  • 你确定它在做什么吗?它应该给你没有欺骗的数组,而不是欺骗。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 2020-04-12
  • 2011-01-31
相关资源
最近更新 更多