求和值,然后添加到表和保持求和?PHP


Summing values then adding to table and keep summing? PHP

基本上我想完成的是:我有一个页面要求

  1. 本金
  2. 利息金额
  3. <
  4. 年变量/gh>

我的问题是本息金额。

当用户点击submit时,它基于year变量创建一个表。例如,

如果year变量==到10,则表有10行。然后第二列是用户输入的本金,第三列是用户输入的利率。

但我的问题是,表显示相同的信息一遍又一遍的所有行。

我需要有第二,第三,第四等行来显示本金+利息金额。

<?php
$_SESSION['intRateSession'] = $intRate;
$_SESSION['totalAmountSession'] = $prinAmount*$intRate;
// Checks if submit is pressed, if so, grabs the $ytd variable to see how many
// times it loops (To create the amount of table rows);
if  (isset($_POST['submit']))
{
    for ($i = 1; $i <= $ytd; ++$i)
    {
        // Print out the amount of table rows based on the amount of years;
?>
        <tr>
          <th> <?php echo "Year " .$i; ?> </th>
          <!-- *** Info to go in the principal amount at year start row *** -->
          <!-- *** Trying to figure this out still *** -->
          <th><?php echo $_SESSION['totalAmountSession']; ?></th>
          <!-- *** Info to go in the interest row *** -->
          <!-- *** Trying to figure this out still *** -->
          <th><?php echo $_SESSION['intRateSession']; ?></th>
        </tr>
<?php
    }
}
?>
</table>

第二行应该显示前一行一直到底部的本金和利息之和。

试试这个:

$amounts = array();
$startAmount = 1000000; // not given in your code?
for ($i = 0; $i < $ytd; ++$i)
{
  $startAmount = $startAmount * $interestRate + $startAmount;
  $amounts[] = array( "year" => $i+1,
                      "amount" => $startAmount,
                      "interest" => $interestRate
  };
}
foreach ( $amounts as $amount )
{
?>
<tr>
  <td><?php echo $amount['year']; ?>
  <td><?php echo $amount['interest']; ?>
  <td><?php echo $amount['amount']; ?>
</tr>
<?php
}

这一小段代码很难提供帮助。下次试着绕一圈,展示问题中涉及的代码的每个部分。例如:在哪里声明$prinAmount变量?从我的角度来看,变量的声明是静态的,期望它们一遍又一遍地显示相同的信息,因为它们没有改变。尝试将$_SESSION['totalAmountSession']声明移动到 FOR循环中,每次迭代递增自己。喜欢的东西:$_SESSION['totalAmountSession']=$_SESSION['totalAmountSession']+($prinAmount*$intRate);确保你正在与数字打交道。好运!