簡體   English   中英

計算元素連續數組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的數量。在示例中,我有3個鏈,但我只想計算其中的2個。 總計結果應為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM