使用PHP CodeIgniter+MySQL实现月度用户营收图表的问题排查
问题定位与解决方案
核心错误分析
你遇到的所有用户营收数据相同的问题,大概率是以下3种原因之一:
- 模型查询未按用户过滤:查询月度营收时没有指定
user_id条件,返回的是全平台总营收而非单个用户数据。 - 控制器循环复用同一数据:只执行一次营收查询,然后将这份数据重复赋值给所有用户。
- 临时数组未重置:循环处理用户时,存储月度数据的数组没有清空,导致新用户数据叠加旧数据。
代码修正示例
1. 修正User模型查询方法
确保查询时按用户ID过滤,返回单个用户的月度营收:
// application/models/User_model.php public function get_user_monthly_revenue($user_id) { return $this->db->select('MONTH(created_at) as month, SUM(revenue) as total') ->from('user_revenues') // 替换为你的营收表名 ->where('user_id', $user_id) ->group_by('month') ->order_by('month', 'ASC') ->get() ->result_array(); } // 补充:获取所有用户的方法(如果已有可忽略) public function get_all_users() { return $this->db->select('id, name') // 按需选择字段 ->from('users') ->get() ->result_array(); }
2. 修正User控制器逻辑
遍历每个用户,单独查询其月度营收,并补全12个月的空数据(避免无营收月份缺失):
// application/controllers/User.php public function user_revenue_chart() { $users = $this->user_model->get_all_users(); $response = []; foreach($users as $user) { // 单独查询当前用户的月度营收 $raw_monthly = $this->user_model->get_user_monthly_revenue($user['id']); // 初始化12个月的营收为0,确保数据结构统一 $formatted_monthly = array_fill(1, 12, 0); foreach($raw_monthly as $item) { $formatted_monthly[(int)$item['month']] = (float)$item['total']; } $response[] = [ 'user_id' => $user['id'], 'user_name' => $user['name'], 'monthly_data' => array_values($formatted_monthly) ]; } // CodeIgniter标准JSON输出 $this->output ->set_content_type('application/json') ->set_output(json_encode($response)); }
3. 修正Chart.js渲染逻辑
确保按用户维度渲染独立的营收曲线:
fetch('/index.php/user/user_revenue_chart') // 替换为你的接口路径 .then(res => res.json()) .then(data => { const ctx = document.getElementById('revenueChart').getContext('2d'); const datasets = data.map(user => ({ label: user.user_name, data: user.monthly_data, borderColor: `rgb(${Math.random()*255|0}, ${Math.random()*255|0}, ${Math.random()*255|0})`, borderWidth: 2, fill: false })); new Chart(ctx, { type: 'line', data: { labels: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'], datasets: datasets }, options: { responsive: true, scales: { y: { beginAtZero: true, title: { display: true, text: '营收金额' } }, x: { title: { display: true, text: '月份' } } } } }); });
验证预期数据格式
修正后接口应返回如下格式(每个用户拥有独立的月度营收数据):
[ { "user_id": 1, "user_name": "张三", "monthly_data": [1200, 1500, 900, 0, 2000, 1800, 1600, 1900, 2200, 2500, 2100, 2800] }, { "user_id": 2, "user_name": "李四", "monthly_data": [800, 1000, 1200, 1100, 1500, 1300, 1400, 1600, 1700, 1900, 1800, 2000] } ]
内容的提问来源于stack exchange,提问作者Jackson
相关产品推荐
相关产品推荐

