php array removing successive duplicate occurances in an array [duplicate]

大憨熊 提交于 2019-12-01 05:44:00

问题


The question i would like to ask here is:

Is there anyway that i can remove the successive duplicates from the array below while only keeping the first one?

The array is shown below:

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

What I want is to have an array that contains:

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

Any suggestions would help. Regards.


回答1:


You can just do something like:

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

Assuming you're not manipulating that array in between you can use current() it's more efficient than counting it each time to check the value at count($a)-1




回答2:


Successive duplicates? I don't know about native functions, but this one works. Well almost. Think I understood it wrong. In my function the 7 => "go" is a duplicate of 6 => "go", and 8 => "stop" is the new value...?

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


来源:https://stackoverflow.com/questions/17711952/php-array-removing-successive-duplicate-occurances-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!