如何计算数组中连续的重复值?

How to count the consecutive duplicate values in an array?(如何计算数组中连续的重复值?)
本文介绍了如何计算数组中连续的重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

$arr = array(1, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3);

我找到了函数 array_count_values(),但它会将所有相同的值分组并计算出现次数,而不考虑连续序列中的中断.

I found the function array_count_values(), but it will group all of the same values and count the occurrences without respecting breaks in the consecutive sequences.

$result[1] = 5
$result[2] = 4
$result[3] = 3

如何对每组连续值进行分组并计算每个序列的长度?请注意,数字 123 有两组序列.

How can I group each set of consecutive values and count the length of each sequence? Notice there are two sets of sequences for the numbers 1, 2, and 3.

我期望生成的数据需要类似于:

The data that I expect to generate needs to resemble this:

[1] = 3;
[2] = 2;
[3] = 2;
[1] = 2;
[2] = 2;
[3] = 1;

推荐答案

只需手动即可:

$arr = array(1,1,1,2,2,3,3,1,1,2,2,3);

$result = array();
$prev_value = array('value' => null, 'amount' => null);

foreach ($arr as $val) {
    if ($prev_value['value'] != $val) {
        unset($prev_value);
        $prev_value = array('value' => $val, 'amount' => 0);
        $result[] =& $prev_value;
    }

    $prev_value['amount']++;
}

var_dump($result);

这篇关于如何计算数组中连续的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)