可以对while或for循环中的变量静态值求和吗?我有代码并正在处理它,但它只对变量求和一次?
这里是我的代码
session_start();
$length=count($_SESSION['product1']);
$shipping2='280';
$shipping3='680';
$newshipping='0';
$newshipping1='0';
$i='0';
while($i= <$length)
{
$newshipping=$shipping2+$shipping3;
$newshipping1=$newshipping+$shipping2;
}
例如,我想要这样
$shipping2='280';
应与$newshipping1
`$newshipping1`= $shipping2='280' + $shipping3='680' = `$newshipping1`=960
+ $shipping2='280'??
'$newshipping1`=960+ $shipping2=280+ $shipping2=280+ $shipping2=280 .....
when ever new product1 enter it should be add $shipping2=280
in the result of `$newshipping1`
我在这里完成了我的代码我的最终代码
$length=count($_SESSION['product1']);
$shipping2=280;
$shipping3=680;
$newshipping=0;
for($i=0; $i <$length; $i++) {
if($i == 1) {
$newshipping = $shipping2+$shipping3;
} else if($i <= 100) {
$newshipping = $newshipping+$shipping2;
}
}
答案 0 :(得分:0)
你的逻辑似乎有点令人困惑,但你可以总结几个整数。如果你想弄清楚几次迭代的最终数量,你应该:
$shipping_one = 680;
$shipping_two = 260;
$shipping_three = 0;
$finalShipping = array();
while($i= <$length)
{
$finalShipping[] = $shipping_one + $shipping_two + $shipping_three;
}
$finalTotal = array_sum($finalShipping);
如果你能澄清你的问题,我可以澄清我的答案。
答案 1 :(得分:0)
这将是((680)+(4 * 280)),就像你在上次评论中解释的一样。
$length = 1;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 2;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 3;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 4;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 5;
echo "Test with $length : ".getShippingTotal($length)." <br />";
function getShippingTotal($length) {
$shipping2=280;
$shipping3=680;
$total = 0;
for($i=0; $i < $length; $i++) {
if($i == 0) {
$total += $shipping2+$shipping3;
} else {
$total += $shipping2;
}
}
return $total;
}
我测试了它,它给了我:
Test with 1 : 960
Test with 2 : 1240
Test with 3 : 1520
Test with 4 : 1800
Test with 5 : 2080