删除数组中连续出现的重复项


Removing successive duplicate occurrences in an array

有没有办法从下面的数组中删除连续的重复项,同时只保留第一个?

阵列如下所示:

$a=array("1"=>"go","2"=>"stop","3"=>"stop","4"=>"stop","5"=>"stop","6"=>"go","7"=>"go","8"=>"stop");

我想要的是一个包含以下内容的数组:

$a=array("1"=>"go","2"=>"stop","3"=>"go","7"=>"stop");

连续重复?我不知道本机函数,但这一个有效。差不多了。我想我理解错了。在我的函数中,7=>"go"是6=>"go)的重复,8=>"stop"是新值。。。?

function filterSuccessiveDuplicates($array)
{
    $result = array();
    $lastValue = null;
    foreach ($array as $key => $value) {
        // Only add non-duplicate successive values
        if ($value !== $lastValue) {
            $result[$key] = $value;
        }
        $lastValue = $value;
    }
    return $result;
}

您可以执行以下操作:

if(current($a) !== $new_val)
    $a[] = $new_val;

假设您没有在两者之间操作该数组,则可以使用current(),这比每次在count($a)-1 检查值时对其进行计数更有效