【问题标题】:codeigniter grouped by, products stock on separate branchcodeigniter 分组,不同分支的产品库存
【发布时间】:2017-05-05 09:24:10
【问题描述】:
在 codeigniter 中,我在数据库中有这个:
product_id product_name stock branch
1 shoe 5 New York
1 shoe 10 Los Angeles
1 shoe 5 Detroit
2 shirt 10 New York
2 shirt 5 Detroit
3 skirt 7 Detroit
我想要实现的是这张表(在视图中):
product_id product_name stock New York Los Angeles Detroit
1 shoe 20 5 10 5
2 shirt 15 10 - 5
3 skirt 7 - - 7
如何在 Codeigniter 3 中编码?
【问题讨论】:
标签:
php
mysql
arrays
codeigniter
【解决方案1】:
首先触发这个查询,
SELECT product_id, product_name, SUM(stock),
GROUP_CONCAT(branch,"#@#",stock) branch_stock FROM your_table GROUP BY product_id
然后你会通过触发这个查询得到数组。
foreach($array as $k => $v){
$temp = explode("#@#", $v['branch_stock']);
$array[$k][$temp[0]] = $temp[2];
}
要获取所有列名,您可以这样做
$columns = array_keys($array);
希望这能解决你的问题。
【解决方案2】:
在模型中:
function product_stock(){
$this->db->select('*');
$this->db->select('SUM(case when branch = "New York" then stock else NULL end) as branch_ny');
$this->db->select('SUM(case when branch = "Los Angeles" then stock else NULL end) as branch_la');
$this->db->select('SUM(case when branch = "Detroit" then stock else NULL end) as branch_dt');
$this->db->from('product');
$this->db->group_by("product_id");
return $this->db->get()->result_array();
}
在视图中:
<table class="table table-striped table-bordered">
<tr>
<th>Produk Id</th>
<th>Produk Nama</th>
<th>New York</th>
<th>Los Angeles</th>
<th>Detroit</th>
</tr>
<?php foreach($allproduct as $e){ ?>
<tr>
<td><?php echo $e['product_id']; ?></td>
<td><?php echo $e['product_name']; ?></td>
<td><?php echo $e['branch_ny']; ?></td>
<td><?php echo $e['branch_la']; ?></td>
<td><?php echo $e['branch_dt']; ?></td>
</tr>
<?php } ?>
对我有用