连续数组php中的元素计数
我有一个数组:连续数组php中的元素计数,php,Php,我有一个数组: $type = ['A','A','A','E','E','E','A','E','A','A','E','E']; 1 2 3 4 5 我打算计算长度大于或等于2的连续链中包含的元素A的数量。在这个例子中,我有三条链,但我只想数其中的两条。总的结果应该是5。查找“CA”的连续链 那么7=>'CA',?试试这个=或者这个=CA-它是数组的一个元素。你试过什么了吗?展示一些代码。 $count = 0;
$type = ['A','A','A','E','E','E','A','E','A','A','E','E'];
1 2 3 4 5
我打算计算长度大于或等于2的连续链中包含的元素
A
的数量。在这个例子中,我有三条链,但我只想数其中的两条。总的结果应该是5。查找“CA”的连续链
那么7=>'CA',?试试这个=或者这个=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;