我正在尝试将数字划分为生成器但是如果之后它少于16,我希望它将数字从较少的16添加到foreach
中的第一个生成器。
$geners = explode(",", $post['geners']); // $post['geners'] = 12,26,988
$count = count($geners); // For example : 3
$calc = (16 / $count); / 5.6666
$total_each = number_format($calc, 0); // 5
$total = ( $count * $total_each); // 15
foreach ($geners as $key=>$gener){
$gener_each = $total_each;
if($total < 16){ // if 15 < 16
$minus_16 = 16 - $total; // 15-16 = 1
$gener_each[0]=$gener_each[0]+$minus_16; // First gener need to add $minus_16
}
echo $gener_each; // Need to be 6,5,5
}
答案 0 :(得分:0)
我不完全明白你需要什么,但这段代码可以帮助你。
$geners = explode(",", $post['geners']); // $post['geners'] = 12,26,988
$count = count($geners); // For example : 3
$calc = (16 / $count); / 5.6666
$total_each = number_format($calc, 0); // 5
$total = ( $count * $total_each); // 15
if($total < 16){
$minus_16 = 16 - $total; //$minus_16 is 1
$gener_each[0] = $total_each + $minus_16; // $gener_each[0] = 6
}
else {
$gener_each[0] = $total_each;
}
for ($x = 1; $x < $count; $x++) {
$gener_each[$x] == $total_each; // $gener_each[1] = 5 and $gener_each[2] = 5
}
for ($x = 0; $x < $count; $x++) {
echo $gener_each[$x]; // print 6,5,5
}
答案 1 :(得分:0)
听起来你需要将16除以任意数字,创建一个数组,其中包含与生成器相同数量的结果,将分割结果的每个实例向下舍入到最接近的整数,然后应用从小数结果到集合中第一个的任何剩余差异。
以下是未经测试的,但请看一下:
$geners = explode(',', $post['geners']);
$firstGener = current($geners);
$count = count($geners);
$calc = (16 / $count);
$floor = floor($calc);
$decimal = $calc - $floor;
$totals = [];
foreach ($geners as $gener) {
$totals[$gener] = $floor;
$totals[$firstGener] += $decimal;
}
//This is just in case a decimal result of an infinite number of digits, truncated by PHP itself, results in this value erroneously looking something like 5.9999999999999
$totals[$firstGener] = round($totals[$firstGener]);
//Since the value of $totals[$geners[0]] isn't done calculating until the completion of the above loop, presentation of each value needs to be handled in a separate one here:
foreach ($totals as $gener => $totals) {
echo "$gener - $total<br>";
}