/**
* Notes: 最大余额法
* User: 曲帅
* DateTime: 2022/2/25 0025 18:12
* @param array $valueList 二维数组 [['count' => 1],['count' => 2],['count' => 3]]
* @param $contKey string 要统计的字段
* @param $precision int 精度
* @param $percentKey int 百分比键名
* @return array
*/
public function getPercentValue(array $valueList, string $contKey, int $precision = 2, $percentKey = 'percent'): array
{
if (count($valueList) === 0) {
return [];
}
$sum = array_sum(array_column($valueList, $contKey));
if ($sum === 0) {
foreach ($valueList as $k => $v) {
$valueList[$k][$percentKey] = 0;
}
return $valueList;
}
$digits = pow(10, $precision);
$currentSum = 0;
$remainder = [];
foreach ($valueList as $k => $v) {
$votesPerQuota = $v[$contKey] / $sum * $digits * 100;
$valueList[$k]['integer'] = (int)$votesPerQuota;
// 余额
$remainder[$k] = $votesPerQuota - $valueList[$k]['integer'];
// 整数总数(会小于真正总数)
$currentSum += $valueList[$k]['integer'];
}
$targetSeats = $digits * 100;
while ($currentSum < $targetSeats) {
$key = array_search(max($remainder), $remainder);
$valueList[$key]['integer']++;
unset($remainder[$key]);
$currentSum++;
}
foreach ($valueList as $k => $v) {
$valueList[$k][$percentKey] = $v['integer'] / $targetSeats;
unset($valueList[$k]['integer']);
}
return $valueList;
}
}
|