I wanted to get the sum of values and limit them with a maximum value. My maximum value is 500.
My array:
array:11 [
0 => 100
1 => 100
2 => 100
3 => 100
4 => 100
5 => 100
6 => 300
7 => 300
8 => 300
9 => 300
10 => 300
11 => 300
12 => 300
13 => 300
14 => 300
15 => 300
]
So each 100 will be sum up to 500 and end up getting this array below.
Desired output:
array:11 [
0 => 300
1 => 300
2 => 300
3 => 300
4 => 300
5 => 300
6 => 300
7 => 500
8 => 500
9 => 500
]
This is what I did so far. Tried to sort all numbers from lowest to highest using usort
.
usort($orderSumArr, function ($a, $b) {
return $a > $b;
});
$sumArr = [];
$current = 0;
foreach ($sumArr as $num) {
if ($current + $num <= 500) { // limit up to 500
$current += $num;
} else {
$sumArr[] = $current;
$current = $num;
}
}
$sumArr[] = $currentSum2;
And this is the output I'm getting. It ends up adding the first 100 which produce 500 and the remaining 100 was added to 300 which sum up to 400.
array:11 [
0 => 300
1 => 300
2 => 300
3 => 300
4 => 300
5 => 300
6 => 300
7 => 300
8 => 300
9 => 400
10 => 500
]