1.核心代码
<?php
function allocateOffsetAmount($records, $offsetAmount) {
$totalFee = array_sum(array_column($records, 'fee'));
$allocatedAmounts = [];
$totalAllocated = 0;
foreach ($records as $index => $record) {
$proportion = $record['fee'] / $totalFee;
$allocatedAmount = round($offsetAmount * $proportion, 2);
$finalAmount = $record['fee'] - $allocatedAmount;
$finalAmount = round($finalAmount,2);
$allocatedAmounts[] = $finalAmount;
$totalAllocated += $allocatedAmount;
}
// 计算偏移量和已分配金额的差值
$difference = round($offsetAmount - $totalAllocated, 2);
// 如果差值大于0,找到最大值的索引并减去差值
if ($difference > 0) {
$maxIndex = array_search(max($allocatedAmounts), $allocatedAmounts);
$allocatedAmounts[$maxIndex] -= $difference;
// 如果差值小于0,找到最小值的索引并加上差值的绝对值
} elseif ($difference < 0) {
$minIndex = array_search(min($allocatedAmounts), $allocatedAmounts);
$allocatedAmounts[$minIndex] += abs($difference);
}
// 检查分配金额中是否有零值
foreach ($allocatedAmounts as $key => $value) {
if ($value == 0) {
// 找到分配金额中最大值的索引
$maxIndex = array_search(max($allocatedAmounts), $allocatedAmounts);
// 将最大值减少0.01
$allocatedAmounts[$maxIndex] -= 0.01;
// 将零值增加0.01
$allocatedAmounts[$key] += 0.01;
}
}
//对数组中大于1,并且有小数点的金额,全部的小数点金额获取出来,加到最小的金额中,s
$decimalSum = 0;
$minIndex = array_search(min($allocatedAmounts), $allocatedAmounts);
foreach ($allocatedAmounts as $key => $value) {
if ($value > 1 && fmod($value, 1) != 0.00) {
$decimalPart = $value - floor($value);
$decimalSum += $decimalPart;
$allocatedAmounts[$key] = floor($value);
}
}
$allocatedAmounts[$minIndex] += round($decimalSum, 2);
//对数组中大于1,并且有小数点的金额,全部的小数点金额获取出来,加到最小的金额中,e
return $allocatedAmounts;
}
// Example usage:
$records = [
['fee' =>300.11 ],
['fee' => 200.88],
['fee' => 100.55],
// ['fee' => 885],
];
$offsetAmount = 0.1;
$allocatedAmounts = allocateOffsetAmount($records, $offsetAmount);
print_r(array_column($records, 'fee'));
echo '<br/>';
print_r($allocatedAmounts);
echo '<br/>';
$totalFee = array_sum(array_column($records, 'fee'));
echo "原总金额: " . $totalFee . "\n";
echo '<br/>';
$totalAmount = array_sum($allocatedAmounts);
echo "返回的数组累加: " . $totalAmount . "\n";