枚举数组并报告索引范围的连续出现次数

时间:2013-01-07 17:30:53

标签: php arrays report indexing frequency

我必须使用什么类型的php数组枚举才能从这个数组中获取:

[0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 42 [5] => 42 [6] => 42 [7] => 42 [8] => 36 [9] => 36 [10] => 0 [11] => 36 [12] => 36 [13] => 36 [14] => 36 [15] => 36 [16] => 42 [17] => 42 [18] => 42 [19] => 42 [20] => 42 [21] => 42 [22] => 42 [23] => 0

报告:

index 0 to index 4   ... 0
index 4 to index 8   ... 42
index 8 to index 16  ... 36
index 16 to index 23 ... 42
index 23             ... 0

提前感谢您的任何帮助。

1 个答案:

答案 0 :(得分:0)

$startIndex = 0;
$endIndex = 0;
$lastVal = $arr[0];

for($i=1; $i<count($arr); $i++) {
   if ($arr[$i] == $lastVal) {
       $endIndex = $i;
   } else {
       echo "index $startIndex to $endIndex ... $lastVal";
       $startIndex = $i + 1;
       $endIndex = $i + 1;
       $lastVal = $arr[$i + 1]
   }
}

我知道当你到达数组的末尾有一些问题,如果索引范围只有1长,但这是一般的想法,绝对应该足以让你前进