我想知道如何将数组拆分为100个块,然后对这些块中的值进行平均。我到目前为止使用array_chunk但无法弄清楚如何平均这些块中的值。这是我的数组的一小部分:
Array ( [0] => 70 [1] => 70 [2] => 70 [3] => 69 [4] => 69 [5] => 69 [6] => 70 [7] => 70 [8] => 70 [9] => 69 [10] => 69 [11] => 70 [12] => 70 [13] => 69 [14] => 70 [15] => 69 [16] => 69 [17] => 70 [18] => 69 [19] => 69 [20] => 69 [21] => 69 [22] => 69 ...
我想要的是以下内容:
[0] => 70(数组中前100个值的平均值)
等等
提前致谢
答案 0 :(得分:3)
$arr = array_chunk(array(1,2,3,4,5,6,7,8,9), 3);
while ($chunk = array_shift($arr)) {
echo array_sum($chunk) / count($chunk) . PHP_EOL;
}
给出:
2
5
8
如果你将每个块更改为4
:
2.5
6.5
9
编辑:100块:
$arr = range(1, 16734, 1);
$arr = array_chunk($arr, ceil(count($arr) / 100));
while ($chunk = array_shift($arr)) {
echo array_sum($chunk) / count($chunk) . PHP_EOL;
}
答案 1 :(得分:1)
$arr = range(1, 200);
$arrs = array_chunk($arr, 5); // 5 is a number of elements in chunk
foreach($arrs as $chunk)
echo array_sum($chunk) / count($chunk) . "\n";
答案 2 :(得分:0)
由于你想要前100的平均值,所以会这样:
$chunks = array_chunk($array, 100);
$sum = round(array_sum($chunks[0]) / count($a), 2);
echo $sum;