使用PHP识别重复模式

时间:2016-03-31 10:38:14

标签: php

我需要找到大于特定浮点数的记录数,并找到重复次数最多的数据组。例如,我有下面的数据,我需要找到有多少条目的值> 4.

 1.5
  1.7
    4.5
    4.7
    4.8
    1.4
    4.5
    4.9

在上述数据中,大于4的最长连续重复值是4.5,4.7,4.8。因此,我想要返回的总数应为3.正如您所看到的那样,模式在4.8之后会中断,因为数字是1.4以上。有没有办法确定这种模式?

3 个答案:

答案 0 :(得分:0)

试试这个,我在这里使用了一个数组:

$arr = array(
        0 => '1.5',
        1 => '1.7',
        2 => '4.5',
        3 => '4.7',
        4 => '4.8',
        5 => '1.4',
        6 => '4.5',
        7 => '4.9'
      );
      $chk_val = 4; // value which is checking
      $cnt = 0;$inc = 0;
      foreach ($arr as $i => $val) {
        if ($val > $chk_val) {
          $inc++;
          if ($inc > $cnt) { $cnt = $inc;}
        } else {
          $inc = 0;
        }
      }
      echo $cnt;

答案 1 :(得分:0)

试试这个

$n = 4; // number to check
$count = 0;
$max = 0;
$ele = array(1.5, 1.7, 4.5, 4.7, 4.8, 1.4, 4.5, 4.9);
for ($i = 0; $i < count($ele); $i++) {
  if ($ele[$i] >= $n) {  // check for greater element than given number
    $count++;    // increase consecutive counter variable 
    $arr[$max] = $count; //save continues max counter to array
  } else {
    $count = 0; //reset consecutive counter 
    $max++;
  }    
}
echo max($arr);

答案 2 :(得分:0)

又快又脏......

function findNums($nums, $min = 4) {
  $groups = array();
  $groupcounts = array();
  $groupindex = 0;
  foreach($nums as $num) {
    if($num > $min) {
      $groups[$groupindex][] = $num;
      if(array_key_exists($groupindex, $groupcounts)) {
        $groupcounts[$groupindex]++;
      } else {
        $groupcounts[$groupindex] = 1;
      }
    } else {
      $groupindex++;
    }
  }
  return array($groupcounts, $groups);
}

// $your_numbers is your list
$nums = array_map('trim', explode("\n", $your_numbers));
$result = findNums($nums);
$counts = $result[0];
$maxcount = max($counts);
$groups = $result[1];
echo "max count is ".$maxcount." with values:\n";
$key = array_search($maxcount, $counts);
var_dump($groups[$key]);