how to group array and count them

2020-03-15 04:31发布

问题:

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;

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


回答2:

What about PHP's array_count_values function?

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)


回答3:

$current = null;
foreach($your_array as $v) {
    if($v == $current) {
        $result[count($result)-1]++;
    } else {
        $result[] = 1;
        $current = $v;
    }
}

var_dump($result);


回答4:

If you don't want the value in array

$result = explode( ',' , implode(',', array_count_values($your_array) ) );


回答5:

Here is the way that I would do it:

function SplitIntoGroups($array)
{
    $toReturnArray = array();
    $currentNumber = $array[0];
    $currentCount = 1;
    for($i=1; $i <= count($array); $i++)
    {
        if($array[$i] == $currentNumber)
        {
            $currentCount++;
        }
        else
        {
            $toReturnArray[] = array($currentNumber, $currentCount);
            $currentNumber = $array[$i];
            $currentCount = 1;
        }
    }

    return $toReturnArray;
}

$answer = SplitIntoGroups(array(1,1,1,2,2,3,3,1,1,2,2,3));
for($i=0; $i<count($answer); $i++)
{
    echo '[' . $answer[$i][0] . '] = ' . $answer[$i][1] . '<br />';
}


回答6:

function findRepetitions($times, $array) {

    $values = array_unique($array);

    $counts = [];
    foreach($values as $value) {
        $counts[] = ['value' => $value, 'count' => 0];
    }

    foreach ($array as $value) {
        foreach ($counts as $key => $count) {
            if ($count['value'] === $value) {
                $counts[$key]['count']++;
            }
        }
    }

    $repetitions = [];
    foreach ($counts as $count) {
        if ($count['count'] === $times) {
            $repetitions[] = $count['value'];
        }
    }

    return $repetitions;
}


标签: php arrays