Here's a solution based on an existing answer about breaking an array into a set number of chunks:
$array = [11, 3, 45, 6, 61, 89, 22];
function array_slimmer(array $array, int $finalCount): array
{
// no work to be done if we're asking for equal or more than what the array holds
// same goes if we're asking for just one array or (nonsensical) less
if ($finalCount >= count($array) || $finalCount < 2) {
return $array;
}
return array_map(function (array $chunk) {
// rounded to two decimals, but you can modify to accommodate your needs
return round(array_sum($chunk) / count($chunk), 2);
}, custom_chunk($array, $finalCount));
}
// this function is from the linked answer
function custom_chunk($array, $maxrows) {
$size = sizeof($array);
$columns = ceil($size / $maxrows);
$fullrows = $size - ($columns - 1) * $maxrows;
for ($i = 0; $i < $maxrows; ++$i) {
$result[] = array_splice($array, 0, ($i < $fullrows ? $columns : $columns - 1));
}
return $result;
}
print_r(array_slimmer($array, 2));
print_r(array_slimmer($array, 3));
print_r(array_slimmer($array, 4));
This outputs:
Array ( [0] => 16.25 [1] => 57.33 )
Array ( [0] => 19.67 [1] => 33.5 [2] => 55.5 )
Array ( [0] => 7 [1] => 25.5 [2] => 75 [3] => 22 )
Demo