CodeIgniter结合MySQL如何实现status列动态分组计数统计
实现方案
第一步:修改模型层统计逻辑
放弃硬编码的SUM(CASE)写法,改用GROUP BY按status_to字段分组统计,自动适配所有存在的状态值:
public function summary($st_date,$end_date){ $this->db->select("status_to, COUNT(*) as count"); $this->db->where('added_date >=', $st_date); $this->db->where('added_date <=', $end_date); $this->db->group_by('status_to'); return $this->db->get('crm_listings'); }
该方法会返回指定时间范围内所有出现过的status_to值,以及对应的记录数量,无需提前预设状态枚举。
第二步:修改控制器层展示逻辑
先整理统计结果为键值对,再动态生成表头和表格内容,全程不需要硬编码状态值:
// 获取统计结果 $status_data = $this->user_model->summary($startDate,$end_date)->result_array(); // 整理为 状态名 => 数量 的键值对,同时收集所有状态名作为表头 $status_count = []; $headers = []; foreach ($status_data as $item) { $status = $item['status_to']; $status_count[$status] = $item['count']; $headers[] = $status; } $output = ' <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr>'; // 动态生成表头 foreach ($headers as $header) { $output .= '<th>'.$header.'</th>'; } $output .= '</tr>'; if (!empty($status_count)) { $output .= '<tr>'; // 动态生成每列数值 foreach ($headers as $header) { $count = isset($status_count[$header]) ? $status_count[$header] : 0; $output .= '<td>'.$count.'</td>'; } $output .= '</tr>'; } else { $output .= '<tr><td colspan="'.(count($headers) ?: 1).'">No Data Found</td>'; } $output .= '</table></div>'; echo $output;
可选优化(查询时间范围内无数据的状态也显示为0)
如果需要把全量表所有存在的status_to值都作为表头展示,哪怕指定时间范围内该状态没有数据也显示为0,可以在控制器中先查询全量状态作为固定表头:
// 先查询全表所有状态作为固定表头 $this->db->select('DISTINCT status_to'); $all_status = $this->db->get('crm_listings')->result_array(); $headers = array_column($all_status, 'status_to'); // 后续统计逻辑不变,未匹配到的状态自动赋值为0
内容的提问来源于stack exchange,提问作者user17071484
相关产品推荐
相关产品推荐

