如何平均每100块数组?

时间:2022-03-27 01:51:52

I'm wondering how to split an array into 100 chunks and then average the values in those chunks. I came as far as using array_chunk but can't figure out how to average the value in those chunks. This is a small part of my array:

我想知道如何将数组分割成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  ...

What I want is the following:

我想要的是:

[0] = > 70 (Average of the first 100 values in the array)

[0] = > 70(数组中前100个值的平均值)

And so on

等等

Thanks in advance

谢谢提前

3 个解决方案

#1


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;
}

http://codepad.org/uaY1ziEI

http://codepad.org/uaY1ziEI

Gives:

给:

2
5
8

And if you change it to 4 per chunk:

如果你把它改成4块

2.5
6.5
9

http://codepad.org/srGW4Rmq

http://codepad.org/srGW4Rmq

EDIT: 100 chunks:

编辑: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;
}

http://codepad.org/t1n9VE35

http://codepad.org/t1n9VE35

#2


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";

#3


0  

Since you want the average for the first 100, something like this will do:

因为你想要前100个的平均值,像这样的东西可以做到:

$chunks = array_chunk($array, 100);
$sum = round(array_sum($chunks[0]) / count($a), 2);

echo $sum;

Example

例子

#1


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;
}

http://codepad.org/uaY1ziEI

http://codepad.org/uaY1ziEI

Gives:

给:

2
5
8

And if you change it to 4 per chunk:

如果你把它改成4块

2.5
6.5
9

http://codepad.org/srGW4Rmq

http://codepad.org/srGW4Rmq

EDIT: 100 chunks:

编辑: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;
}

http://codepad.org/t1n9VE35

http://codepad.org/t1n9VE35

#2


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";

#3


0  

Since you want the average for the first 100, something like this will do:

因为你想要前100个的平均值,像这样的东西可以做到:

$chunks = array_chunk($array, 100);
$sum = round(array_sum($chunks[0]) / count($a), 2);

echo $sum;

Example

例子