如果使用codeigniter在数据库中不存在任何月份,如何显示0?

fzwojiic  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(106)

例如,我的dB database data中有以下数据
并且我希望对按月份分组的条目进行计数。此外,我希望对DB中不存在的月份显示计数0。
下面是我使用Codeigniter编写的代码片段:

$result = $builder->select('COUNT(insta_alert_id), MONTH(created_at)')
            ->where("created_at BETWEEN '2022-04-01' AND '2023-07-31'")
            ->where('school_id', $loginDt['school_id'])
            ->groupBy('YEAR(created_at)')
            ->groupBy('MONTH(created_at)')
            ->get()
            ->getResultArray();

        $data = array();

        if (!empty($result)) {
            $rowDt = array();
            foreach ($result as $dt) {
                $rowDt['count'] = $dt['COUNT(insta_alert_id)'];
                $rowDt['month'] = $dt['MONTH(created_at)'];
                $data[] = $rowDt;
            }
        }

我在Postman中得到如下结果:

"data": [
    {
        "count": "11",
        "month": "4"
    },
    {
        "count": "6",
        "month": "5"
    },
    {
        "count": "1",
        "month": "6"
    }
]

而我想要的是:

"data": [
        {
            "count": "0",
            "month": "1",
        },
        {   "count": "0",
            "month": "2"
        },
        {
            "count": "0",
            "month": "3"
        {
            "count": "11",
            "month": "4"
        },
        {
            "count": "6",
            "month": "5"
        },
        {
            "count": "1",
            "month": "6"
        }
        .
        .
        .
    ]
ssm49v7z

ssm49v7z1#

您可以填写缺少的月份:
1.收集所有填写月份
1.运行12个月并填空

$existingMonths = array_reduce(
    $data,
    function ($months, $item) {
         $months[$item['month']] = $item['month'];

         return $months;
    },
    []
);

for ($i = 1; $i <= 12; $i++) {
    if (!isset($existingMonths[$i])) {
        $data[] = [
            'count' => 0,
            'month' => $i,
        ];
    }
}

相关问题