Jeg Bagus Jeg Bagus - 6 months ago 8
PHP Question

how to group array and count them

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;

Answer

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