如何组阵列和尽数 [英] how to group array and count them

查看:143
本文介绍了如何组阵列和尽数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组这样

  $ ARR =阵列(1,1,1,2,2,3,3,1,1,2,2,3);

我发现一个函数 array_count_values​​ 。但它会组中的所有相同的值并计算所有这些,打破序列。

  $结果[1] = 5
$结果[2] = 4
$结果[3] = 3

如何创建计数阵列组将按照顺序。结果我真正想要的是:

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


解决方案

它可以简单地手工完成:

  $ ARR =阵列(1,1,1,2,2,3,3,1,1,2,2,3);$结果=阵列();
$prev_value =阵列('值'=>空,'量'=> NULL);的foreach($改编为$ VAL){
    如果($prev_value ['值']!= $ VAL){
        未设置($prev_value);
        $prev_value =阵列('值'= GT; $ VAL,'量'= 0);
        $结果[] =&放大器; $prev_value;
    }    $prev_value ['量'] ++;
}后续代码var_dump($结果);

i have array like this

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

i found one function array_count_values. but it will group all same value and count them all and break the sequence.

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

how to create group of count array that will follow the sequence. the result i really want is :

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

解决方案

It can be done simply manually:

$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);

这篇关于如何组阵列和尽数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆