Listening to the Words

php统计一个一维数组中,相同的值连续出现的最大次数

一维数组:

$array = [0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0];

$a = [];
$tmp = 0;
$count = 1;

foreach ($array as $k => $v) {
    if ($tmp == 0) {
        $tmp = $v;
        continue;
    }

    if ($tmp == $v) {
        $count++;
    } else {
        if(isset($a[$tmp])){
            if ($a[$tmp] < $count) {
                $a[$tmp] = $count;
            }
        } else {
            $a[$tmp] = $count;
        }

        $tmp = $v;
        $count = 1;
    }

    if (!isset($array[$k+1])) {
        if(isset($a[$v])){
            if ($a[$v] < $count) {
                $a[$v] = $count;
            }
        } else {
            $a[$v] = $count;
        }
    }
}

print_r($a);

Array ( [1] => 2 [0] => 1 )

点赞