我正在嘗試根據其他變數值增加變數值,例如:
我有一個名為 $totalhousesleft 的變數...
我想根據我有多少 $totalhousesleft 來設定價格...
每次 totalhousesleft 減少 10 時,我想將變數 $currentprice 增加 1。
$totalhouses left 的起始值為 8000,每次下降 10,我設定 $currentprice 1 ...當前價格的起始值為 9...
就像是:
If ($totalhousesleft >= 8000) {$currentprice = 9; $sellingprice = 8;}
If ($totalhousesleft >= 7990) {$currentprice = 10; $sellingprice = 9;}
If ($totalhousesleft >= 7980) {$currentprice = 11; $sellingprice = 10;}
If ($totalhousesleft >= 7970) {$currentprice = 12; $sellingprice = 11;}
一直到房子剩下 1 個。如果有人可以給我看一個回圈或更短的代碼,我將不勝感激!
uj5u.com熱心網友回復:
@elias-soares 答案很接近,但缺少ceil……和解釋。
foreach ( [8000, 7995, 7990, 7985, 7980, 7975, 7970, 7965] as $totalhousesleft ) {
$currentprice = 9 ((ceil(800 - ((min(8000, $totalhousesleft)) / 10))) * 1);
$sellingprice = $currentprice - 1;
}
在這里試試:https ://onlinephp.io/c/68196
讓我們分解如何獲取$currentprice:
//$currentprice = ceil(9 (800 - (min(8000, $totalhousesleft) / 10)));
// get the lesser of 8000, or $totalhousesleft
// in other words, 8000 is the maximum number to calculate
$totalhousesleft = min(8000, $totalhousesleft);
// divide total houses left into number of tenth units
$tenth = $totalhousesleft / 10;
// since the price increases when the number of tenth units decreases,
// the unit factor is the difference between the max possible tenths
// and tenths of the current total houses left
$tenthunit = 800 - $tenth;
// tenth unit is fractional for values not evenly divisible by 10,
// so round up
$tenthroundup = ceil($tenthunit);
// multiply the number of tenth units with the price per unit
$pricepertenth = $tenthroundup * 1; // 1 currency per tenth unit
// add the price per tenth cost to the base cost (9 currency)
$currentprice = 9 $pricepertenth;
獎勵:這可以在一個函式中實作:
function getPrices ($totalhousesleft, $baseprice = 9, $discount = 1, $priceperunit = 1, $maxtotal = 8000, $units = 10) {
$currentprice = $baseprice ((ceil(($maxtotal / $units) - ((min($maxtotal, $totalhousesleft)) / $units))) * $priceperunit);
return [$currentprice, $currentprice - $discount];
}
foreach ( [8000, 7995, 7990, 7985, 7980, 7975, 7970, 7965] as $totalhousesleft ) {
list($currentprice, $sellingprice) = getPrices($totalhousesleft);
}
在這里試試:https ://onlinephp.io/c/2672b
uj5u.com熱心網友回復:
可以為此使用orfor回圈。while我會使用for:
$iteration = 0;
for($x = 8000; $x > 0; $x = $x - 10){
if(empty($iteration)) {
$iteration = $x/1000;
}
if ($totalhousesleft >= $x) {
$currentprice = $iteration;
$sellingprice = $currentprice 1;
break;
}
$iteration ;
}
if(empty($currentprice)){
$currentprice = $iteration;
$sellingprice = $currentprice 1;
}
這會迭代直到找到匹配項,然后退出回圈。價格基于它所在的迭代。
演示鏈接:https ://3v4l.org/Mm432 (針對邊緣情況 0-9 更新)
uj5u.com熱心網友回復:
您可以使用數學。
$currentprice = 9 (800 - (min(8000,$totalhousesleft)/10));
$sellingprice = $currentprice - 1;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494950.html
上一篇:使用javascript函式計算Innerwidth和innerheight
下一篇:如何在R中從最高到最低排序
