我想通过(SQL(在组中创建子组。在我的情况下,我想在分组详细信息中进行分类,它来自两个不同的列,要了解更多详细信息,请查看:
我有这样的sql表:
+----+-------+--------+-------+
| No | data1 | detail | price |
+----+-------+--------+-------+
| 1 | ID1 | Food | $ 100 |
| 2 | ID1 | Drink | $ 25 |
| 3 | ID2 | Drink | $ 25 |
| 4 | ID1 | Snack | $ 50 |
| 5 | ID2 | Snack | $ 50 |
+----+-------+--------+-------+
我想在我的php页面上做出这样的结果:
+----+-------+--------+-------+
| No | detail_lunch | price |
+----+-------+--------+-------+
| 1 | Food | |
| | - ID1 | $ 100 |
| 2 | Snack | |
| | - ID1 | $ 25 |
| | - ID2 | $ 25 |
| 3 | Drink | |
| | - ID1 | $ 10 |
| | - ID2 | $ 10 |
+----+-------+--------+-------+
我已经尝试了以下CONCAT组:
控制器:
$d['data'] = $this->db->query("select detail_item, GROUP_CONCAT (detail) detail_lunch
from table ORDER BY detail_lunch ASC");
视图:
<?php
foreach($data->result_array() as $d)
{
?>
<tr>
<td><?php echo $no; ?></td>
<td><?php echo $d['detail_lunch']; ?></td>
<td><?php echo $d['price']; ?></td>
</tr>
<?php
$no++;
}
?>
我上面的代码不起作用,有什么建议可以解决我的问题吗?
谢谢。。。
GROUP BY
,因为您没有使用聚合函数(将两行值合并为一个值(,您正试图创建一个数据透视表,(将相关列下的两列连接为多行(。您只需要ORDER BY detail ASC, data1 ASC
,在结果集发生变化时迭代以显示detail
,否则显示data1
和price
示例:https://3v4l.org/7tVDS
查询:
$data = $this->db->query('SELECT data1, detail, price
FROM table ORDER BY detail ASC, data1 ASC');
视图:
<?php
//...
$no = 1;
$currentDetail = null;
foreach ($data->result_array() as $d) {
if ($d['detail'] !== $currentDetail) { ?>
<!-- Only Show the Detail when changed -->
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $d['detail']; ?></td>
<td> </td>
</tr>
<?php } ?>
<!-- Always show the data1/price on subsequent row -->
<tr>
<td> </td>
<td>- <?php echo $d['data1']; ?></td>
<td><?php echo $d['price']; ?></td>
</tr>
<?php
$currentDetail = $d['detail'];
} ?>
结果:
| 1 | Food |
| - ID1 | $ 100 |
| 2 | Drink |
| - ID1 | $ 25 |
| - ID2 | $ 25 |
| 3 | Snack |
| - ID1 | $ 50 |
| - ID2 | $ 50 |
或者,您可以操作数据在视图中的显示方式,例如使用明细表列td
中的无序列表ul
以及价格。通过使用PHP在有组织的关联数组中,按照您希望它们在视图中显示的方式来组织值。
示例:https://3v4l.org/8sIrR
$dataArray = [];
foreach ($data as $d) {
if (!array_key_exists($d['detail'], $dataArray)) {
$dataArray[$d['detail']] = [];
}
$dataArray[$d['detail']][] = $d;
}
//...
$no = 1;
foreach ($dataArray as $detail => $d) { ?>
<tr>
<td><?php echo $no++; ?></td>
<td>
<?php echo $detail; ?>
<ul>
<?php foreach ($d as $v) { ?>
<li><?php echo $v['data1']; ?> <?php echo $v['price']; ?></li>
<?php } ?>
</ul>
</td>
</tr>
<?php } ?>
查询是个问题。按明细从表组中选择detail_lunch。然后可以对该结果使用if语句。我在电脑上工作后会更新我的答案。