计数元素连续数组 PHP


count elements consecutive array php

我有数组:

$type = ['A','A','A','E','E','E','A','E','A','A','E','E'];
          1   2   3                       4   5

我打算计算长度大于或等于 2 的连续链中包含的元素A的数量。在示例中,我有三条链,但我只想数其中的两条。总结果应为 5。

查找"CA"的连续链

$count = 0;
$link = array();                     // Here will be chain lengths
array_push($types, '');              // to work if the last item == 'CA'
foreach($types as $item) 
  if ($item == 'CA') $count++;       
  else if ($count) 
         { $link[] = $count; $count = 0; }  
rsort($link);                        // 3, 2, 1
$sum = 0;
foreach ($link as $i) 
   if ($i >= 2) $sum += $i;          // Count result
   else break;                       // Further chains are shorter than we want
echo $sum;