我有下表
|id|user_type|
|1|Customers|
|2|Suppliers|
|3|Customers|
|4|Suppliers|
|5|Suppliers|
|6|Employees|
我想要计算总客户,供应商,员工
这是我的HTML
<a href="#" class="customers list-group-item">
<span class="badge badge-info">
2
</span>
Customers
</a>
<a href="#" class="employees list-group-item">
<span class="badge badge-danger">
3
</span>
Employees
</a>
<a href="#" class="suppliers list-group-item">
<span class="badge badge-success">
1
</span>
Suppliers
</a>
我的查询代码如下所示
<?php
$this->load->model("User_model");
$query = $this->db->query('SELECT user_type, COUNT(Customers) AS total FROM `users` GROUP BY user_type');
if ($query->num_rows() > 0)
foreach ($query->result() as $row)
$data['users'] = array(
'total' => $row->total,
);
echo $data['users'];
此代码无效。谢谢你的时间。
答案 0 :(得分:1)
在$data['users']
的每次迭代中,您的foreach
变量都会被覆盖。
您需要做的是将新项目添加到$data['users']
。使用[]
:
foreach ($query->result() as $row) {
$data['users'][] = array(
'type_name' => $row->user_type,
'total' => $row->total,
);
}
// `echo` will no work with `arrays`, use `print_r` instead
print_r($data['users']);