Home >Backend Development >PHP Tutorial >php take value in range and make sum to 100
<?php $n = array( '0' => '1.1-4.6', '1' => '1.2-33.7', '2' => '1.3', '3' => '1.4-30', '4' => '15-44', '5' => '1.1-4.6', '6' => '1.2-33.7', '7' => '1.3', '8' => '1.4-43.9', '9' => '9.5-44', ); $nn = check_zifu($n); for ($ii=0; $ii < count($nn); $ii++) { if (count($nn[$ii]) > 1) { //判断是否是范围,若不是,左边界值和右边界值相同 $nnn[$ii]['min'] = ceil($nn[$ii][0]); $nnn[$ii]['max'] = floor($nn[$ii][1]); }else{ $nnn[$ii]['min'] = $nn[$ii][0]; $nnn[$ii]['max'] = $nn[$ii][0]; } } $nnnn = getNum($nnn); echo "<pre class="brush:php;toolbar:false">"; print_r($nnnn); function check_zifu($a){ $c = array(); for ($i=0; $i < count($a); $i++) { $r = strpos($a[$i],'-'); if($r == ''||$r == false||$r == null){ $r = strpos($a[$i],'~'); if($r == ''||$r == false||$r == null){ $c[$i][0] = $a[$i]; }else{ $b = explode('~', $a[$i]); $c[$i] = $b; } }else{ $b = explode('-', $a[$i]); $c[$i] = $b; } } return $c; } function getNum($arr){ for ($i=0; $i < count($arr); $i++) { $c['min'][$i] = $arr[$i]['min']; $c['max'][$i] = $arr[$i]['max']; } $min_sum = array_sum($c['min']); //计算左边界值之和 $max_sum = array_sum($c['max']); //计算右边界值之和 if($min_sum < 100 && $max_sum > 100){ //若左边界值和大于100或右边界值和小于100,不成立 for ($iii=0; $iii < count($c['min']); $iii++) { //从第一位左边界值开始加一 $max = $c['max'][$iii]; while ($c['min'][$iii]+1 <= $max) { //判断是否超出右边界值 $c['min'][$iii] = $c['min'][$iii]+1; if (array_sum($c['min']) == 100) { return $c['min']; break; }else if (array_sum($c['min']) > 100) { $c['min'][$iii] = $c['min'][$iii] - (array_sum($c['min']) - 100); return $c['min']; break; } } } }else if($min_sum == 100){ //若左边界值和为100 for ($ii=0; $ii < count($c['min']); $ii++) { $n[$ii] = $c['min'][$ii]; } return $c['min']; }else if($max_sum == 100){ //若右边界值和为100 for ($iiii=0; $iiii < count($c['max']); $iiii++) { $n[$iiii] = $c['max'][$iiii]; } return $c['min']; }else{ echo 'error'; } } ?>
The above introduces how PHP takes a value in a range and makes the sum be 100, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.