我想你需要
intdiv
和模
%
:
$packagesCount = count($packages);
$averageWeight = $totalWeight/$packagesCount;
$wholeWeight = intdiv($totalWeight,$packagesCount);
$weightRest = $totalWeight % $packagesCount;
// totalWeight = wholeWeight * packagesCount + weightRest
$i = 0;
foreach ($packages as $key => $package) {
$w = $wholeWeight;
if ($i < $weightRest) {
$w += 1;
}
$i+= 1;
$packages[$key]['Weight'] = $w;
}
我们的想法是,每个包至少有
英迪夫
重量和第一
weightRest
包装重量将增加1。以这种方式,你将完全符合你的
totalWeight
.
也见
online demo
p.s.php不是我的语言,因此代码可能非常不惯用。不过,我还是希望它能传达这个想法。