我有一个像:
这样的数组array[
'5' => 142,
'2' => 57,
'18' => 37
];
我需要将这个数组分成50个串,所以输出为:
array[
'0' => ['5' => 50],
'1' => ['5' => 50],
'2' => ['5' => 42, '2' => 8],
'3' => ['2' => 49, '18' => 1],
'4' => ['18' => 36],
];
有人可以帮助在PHP中提供某些解决方案或逻辑或任何现有功能吗?
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以尝试这样的事情:
$total = [] ; $ckey = 0 ;
foreach ($array as $key => $value) {
while ($value) {
$cursum = isset($total[$ckey]) ? array_sum($total[$ckey]) : 0 ;
if ($cursum == 50) $ckey++ ;
if ($value + $cursum > 50) $add = 50 - $cursum ;
else $add = $value ;
$total[$ckey][$key] = $add ;
$value -= $add ;
}
}
print_r($total) ;
输出:
Array (
[0] => Array (
[5] => 50
)
[1] => Array (
[5] => 50
)
[2] => Array (
[5] => 42
[2] => 8
)
[3] => Array (
[2] => 49
[18] => 1
)
[4] => Array (
[18] => 36
)
)