Home  >  Article  >  Backend Development  >  php take value in range and make sum to 100

php take value in range and make sum to 100

WBOY
WBOYOriginal
2016-07-28 08:27:56942browse
<?php
	$n = array(
		&#39;0&#39; => '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],&#39;-&#39;);
		if($r == &#39;&#39;||$r == false||$r == null){
			$r = strpos($a[$i],&#39;~&#39;);
			if($r == &#39;&#39;||$r == false||$r == null){
				$c[$i][0] = $a[$i];
			}else{
				$b = explode(&#39;~&#39;, $a[$i]);
				$c[$i] = $b;
			}
		}else{
			$b = explode(&#39;-&#39;, $a[$i]);
			$c[$i] = $b;
		}
	}
	
	return $c;
}

function getNum($arr){
	for ($i=0; $i < count($arr); $i++) { 
		$c[&#39;min&#39;][$i] = $arr[$i][&#39;min&#39;];
		$c[&#39;max&#39;][$i] = $arr[$i][&#39;max&#39;];
	}
	$min_sum = array_sum($c[&#39;min&#39;]);		//计算左边界值之和
	$max_sum = array_sum($c[&#39;max&#39;]);		//计算右边界值之和
	if($min_sum < 100 && $max_sum > 100){	//若左边界值和大于100或右边界值和小于100,不成立
		for ($iii=0; $iii < count($c[&#39;min&#39;]); $iii++) { 	//从第一位左边界值开始加一
			$max = $c[&#39;max&#39;][$iii];
			while ($c[&#39;min&#39;][$iii]+1 <= $max) {				//判断是否超出右边界值
				$c[&#39;min&#39;][$iii] = $c[&#39;min&#39;][$iii]+1;
				if (array_sum($c[&#39;min&#39;]) == 100) {
					return $c[&#39;min&#39;];
					break;
				}else if (array_sum($c[&#39;min&#39;]) > 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[&#39;min&#39;]); $ii++) { 
			$n[$ii] = $c[&#39;min&#39;][$ii];
		}
		return $c[&#39;min&#39;];
	}else if($max_sum == 100){		//若右边界值和为100
		for ($iiii=0; $iiii < count($c[&#39;max&#39;]); $iiii++) { 
			$n[$iiii] = $c[&#39;max&#39;][$iiii];
		}
		return $c[&#39;min&#39;];
	}else{
		echo &#39;error&#39;;
	}
}
?>

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Nginx安装启动Next article:php入门4 解析json对象