<?php
function CalculateAverage(array $data) {
//return array with the firs item from every group and make sum from this array
$sum = array_sum(array_map(function ($item) {
return $item[0];
}, $data)); //temp variable for calculate the average
$temp = 0;
//itreate through the group
for ($i = 0; $i < sizeof($data); ++$i) {
$temp += ($data[$i][0] * $data[$i][1]);
}
//get the average
return $temp / $sum;
}
function GetGroup($size, $total, $decrease, $stages) {
$group = array();
for ($i = 0; $i < $size - 1; ++$i) {
array_push($group, array($decrease, $stages[$i]));
}
array_push($group, array($total - (($size - 1) * $decrease), $stages[$size - 1]));
return $group;
}
$sales = 200;
$stages = array(0.3, 0.35, 0.5, 0.75);
$main_factor = 20;
$max_stage = 3;
$stages_params = array(0 => $stages[0]);
for ($i = 1; $i <= $max_stage; ++$i) {
array_push($stages_params, GetGroup($i + 1, $sales, $main_factor, $stages));
}
$stage_index = (floor($sales / $main_factor) > $max_stage) ? $max_stage : floor($sales / $main_factor);
if (!isset($avg) && $stage_index !== 0) {
$avg = CalculateAverage($stages_params[$stage_index]);
}
echo "<pre>";
print_r( $stages_params);
echo $avg;
?>