0

是否可以在 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;
}
}
4

2 回答 2

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);

如果你能澄清你的问题,我可以澄清我的答案。

于 2013-06-05T21:48:59.147 回答
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 
于 2013-06-05T21:59:59.713 回答