【问题标题】:PHP social contribution YearlyPHP 社会贡献 每年
【发布时间】:2022-01-01 20:23:33
【问题描述】:

我正在使用 PHP 编写系统报告。我有一个包含两列(付款日期和金额)的表格。

如何使用 while 循环来计算每年 12 月之后的总金额?我尝试按照随附的屏幕截图执行此操作,但在每年 12 月之后显示的总和是错误的。

以下是我的做法:

 <?php 
    $total=0;
    $s = date('m');
    $c = mysqli_query($con,"SELECT * FROM payroll_contribution_pssf WHERE employee_id='3' ORDER BY contribution_id ASC");
    while($array = mysqli_fetch_array($c))
    {
        $m = date('m', strtotime($array['payroll_date']));
        echo $array['payroll_date']." ".$array['employee_amount']."<br>";
        if($m==12)
        {
        if($total == 0)
        $total = $array['employee_amount'];
        $total = $total + $array['employee_amount'];
        echo number_format($total,0)."<br>";  
        }
    }
    
    
    ?>

【问题讨论】:

  • 请不要只显示屏幕截图然后谈论您应该尝试的内容,而是向我们展示您实际做了什么 - 代码! How to Ask, minimal reproducible example
  • $total=0; $s = 日期('m'); $c = mysqli_query($con,"SELECT * FROM payroll_contribution_pssf WHERE employee_id='3' ORDER BY contribution_id ASC"); while($array = mysqli_fetch_array($c)) { $m = date('m', strtotime($array['payroll_date'])); echo $array['payroll_date']." ".$array['employee_amount']."
    "; if($m==12) { if($total == 0) $total = $array['employee_amount']; $total = $total + $array['employee_amount']; echo number_format($total,0)."
    ";
  • 请不要在 cmets 中显示扩展的 sn-ps 代码,这很难阅读。编辑我们的问题并把它放在那里,格式正确stackoverflow.com/help/formatting
  • 我已经更新了问题。很抱歉给您带来不便
  • 您总结这些值的逻辑毫无意义。对于初学者,您通过将整个“计算”包装到 if($m==12) { ... }忽略所有上个月的值

标签: php sql


【解决方案1】:

您似乎希望它计算并显示自上次计算总和以来所有先前行的总价值(或自数据集开始以来,在第一次迭代的情况下)。

在这种情况下,你的逻辑缺陷在于你是

a) 仅在第 12 个月时才加入总数,并且

b) 到了第 12 个月后,您不会重置它。

您需要有一个“总”变量,每次循环时都会递增,并且您还需要在显示后将其重置为 0。

例如:

$total = 0;
$c = mysqli_query($con,"SELECT * FROM payroll_contribution_pssf WHERE employee_id='3' ORDER BY contribution_id ASC");

while ($array = mysqli_fetch_array($c))
{
    $m = date('m', strtotime($array['payroll_date']));
    echo $array['payroll_date']." ".$array['employee_amount']."<br>";
    $total += $array['employee_amount']; //increment every time

    if ($m == 12)
    {
        echo number_format($total, 0)."<br>";
        $total = 0; //reset after displaying
    }
}

【讨论】:

  • 为什么要声明$s?所以基本上,OP需要在打印年度总数后删除if($total == 0)条件并添加$total =0?我不确定这个问题需要更多关注。
猜你喜欢
  • 2017-04-03
  • 2019-03-15
  • 2014-10-16
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2011-09-13
  • 2011-08-15
相关资源
最近更新 更多