所以我有一个值数组
-webkit-transform: translate(-50%,-50%);
-webkit-transform: -webkit-translate(-50%,-50%);
这个$ get_wholeUnits []具有以下值
if(isset($wholeprices) && !empty($wholeprices)){
foreach($wholeprices as $wholeprice){
$get_wholeUnits[] = $wholeprice->Units;
$get_wholePrices[] = $wholeprice->UnitsPrice;
}
此$ get_wholePrices []具有以下值
array(
0=>200,
1=>150
);
现在我有一个数字350,我希望它只计算为200,最接近350的200.但如果我的数字为190,那么它应该用150计算,因为它是最接近的。
由于我的代码(350)在第一个索引处有200,而第一个if条件为true,它将产生值,但同时,在第二个索引处,if条件再次执行。< / p>
我只想要一个简单的行为,无论数字是什么,它都应该识别最接近的数字而不管它们属于哪个索引。
答案 0 :(得分:1)
您必须处理整个数组才能找到最接近的值。
你需要做这样的事情
$valueToCompare = 300;
$arrayOfvalues = [/*Some different values here*/];
$closestValue = arrayOfvalues[0];
for($i=1; $i<count($arrayOfvalues);$i++){
if(abs($valueToCompare - $closestValue) > abs($valueToCompare - $arrayOfvalues[$i]))
$closestValue = $arrayOfvalues[$i];
}
最后,您将获得$closestValue
变量中数组中最接近的值。
答案 1 :(得分:0)
如果我得到你的要求,我不是百分之百,但如果我没错,那就行了。
for($get_whol_price=0;$get_whol_price<count($get_wholeUnits);$get_whol_price++){
if(350 >= $get_wholeUnits[$get_whol_price]){
$wholesale_price_Set = $get_wholeUnits[$get_whol_price];
$gross_price = 350 * $get_wholePrices[$get_whol_price];
break; //This will exit from for loop since you have the value that you wants.
}
}
}