给定以下数组:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
并假设$n = 2
,在每个值内获取数组中每个值的计数的最有效方法是什么$n
?
例如,在5、7、76
内有 3 个其他值。$n
最终,我想要一个相应的数组,其中包含简单的计数$n
,如下所示:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
一个简单的 foreach 循环是要走的路吗?键盘链接
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);