【问题标题】:How can I display 0 if there doesn't exist any month in the database using codeigniter?如果使用 codeigniter 数据库中不存在任何月份,我如何显示 0?
【发布时间】:2022-08-02 15:27:11
【问题描述】:

例如,我的 dB 中有以下数据 database data

我想计算按月分组的条目。此外,我想为那些在 dB 中不存在的月份显示计数为 0。

这是我使用 Codeigniter 的代码 sn-p:

$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\"
        }
        .
        .
        .
    ]
  • 你必须左加入一个包含一系列行的表,你想在你的情况下显示 1-12

标签: php mysql sql database codeigniter


【解决方案1】:

您可以填写缺少的月份:

  1. 收集所有填充的月份
  2. 历时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,
            ];
        }
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多