How to group an array and count them

I have an 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 he will group all the same meaning and count them all and break the sequence.

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

how to create a count array group that will follow a sequence. the result that I really want:

 [1] = 3; [2] = 2; [3] = 2; [2] = 2; [3] = 1; 
+4
source share
6 answers

This 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); 
+3
source

What about the 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 ) 
+12
source
 $current = null; foreach($your_array as $v) { if($v == $current) { $result[count($result)-1]++; } else { $result[] = 1; $current = $v; } } var_dump($result); 
+2
source

If you do not want the value in the array

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

Here's how to 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 />'; } 
0
source
 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; } 
0
source

Source: https://habr.com/ru/post/1343107/


All Articles