- array_sum: documentation ( source)
- var_export: documentation ( source)
- min: documentation ( source)
<?php
$array = [
'5' => 142,
'2' => 57,
'0' => 0,
'18' => 37,
'3' => 13,
'6' => 101,
];
$groupLimit = 50;
$result = [];
$groupKey = 0;
foreach ($array as $key => $value) {
while ($value) {
$sum = array_sum($result[$groupKey] ?? []); // get group sum
$value -= $result[$groupKey][$key] = min($groupLimit - $sum, $value); // push key with limited value; decrease value
$groupKey += ($sum + $result[$groupKey][$key] === $groupLimit); // only increment group key if at $groupLimit
}
}
var_export($result);