数组和php中的计算

乔恩

我有数据数组

      [
        {
            "month": 1,
            "total_now": "3,000"
            "total_before": "2,000"
        },
        {
            "month": 2,
            "total_now": "1,000"
            "total_before": "3,000"
        },
        {
            "month": 3,
            "total_now": null 
            "total_before": "1,000"
        },
        .........
        {
            "month": 12,
            "total_now": null,
            "total_before": "20,422"
        },
    ]

这里我显示了2020年和2021年的月报表数据我有一个类似上面数组的结果,如何按月计算上面的总数据?如果在 2020 年 1-12 个月的总数是完整的,但对于当前年份到第 8 个月,则第 9-12 个月为空。我想计算一下。

这是我的代码

public function loop_get(){
  $thn_now = date('Y'); 
  $thn_before = date('Y') -1; 
  $result = [];
      for ($month = 1; $month <= 12; $month++) {
            $result[] = [
                'month' => $month,
                'total_now' => $this->model->dbget($thn_now ,$month)->row()->total?? null
                'total_before' => $this->model->dbget($thn_before,$month )->row()->total?? null,
            ];
        }
    }

如何根据月份指数计算或求和?

ex : [arr[0]+arr[1]+arr[2] ....]

我想要这样的输出

 [
        {
            "month": 1,
            "total_now": "3,000"
            "total_before": "2,000" 
        },
        {
            "month": 2,
            "total_now": "1,000" // arr[0] + arr[1] = value 4000
            "total_before": "3,000" // arr[0] + arr[1] = value 5000
        },
        {
            "month": 3,
            "total_now": null 
            "total_before": "1,000" // arr[0] + arr[1] + arr[2] = value 6000
        },
        .........
        {
            "month": 12,
            "total_now": null,
            "total_before": "20,422" // arr[0] + arr[1] + arr[2] ..... = 20000
        },
    ]
米克马克库萨

我假设您正在处理整数值并且您的逗号代表数千个占位符。这些需要消毒以允许添加。

我已经包含了这些null检查,它假设一旦在当前年份遇到一个空日期,就不会有后续的数值。

代码:(演示

public function GetMonthlyTotalsSincePreviousYear($year = null): void
{
    $thisYear = $year ?? date('Y');
    $lastYear = $thisYear - 1;
    $thisYearRunningTotal = 0;
    $lastYearRunningTotal = 0;
    $result = [];
    for ($month = 1; $month <= 12; ++$month) {
        $thisYearMonthTotal = $this->My_model->model_month($month, $thisYear)->row()->hasil;
        $thisYearRunningTotal = $thisYearMonthTotal === null
            ? null
            : (int)str_replace(',', '', $thisYearMonthTotal) + $thisYearRunningTotal;
        
        $lastYearMonthTotal = $this->My_model->model_month($month, $lastYear)->row()->hasil;
        $lastYearRunningTotal = $lastYearMonthTotal === null
            ? null
            : (int)str_replace(',', '', $lastYearMonthTotal) + ($lastYearRunningTotal ?? 0);

        $result[] = [
            'month' => $month,
            'total_now' => $thisYearRunningTotal,
            'total_before' => $lastYearRunningTotal,
        ];
    }
    $this->set_response($result, 200);  
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章