【发布时间】:2015-01-05 08:09:32
【问题描述】:
我正在尝试按名为“组”的列对数据进行分组。我一直在看这篇文章Categorizing mysql data into seperate html tables?
这也适用于我的情况,但相同的组会分开
原来是这样的
_____________________________________
|_____________Group ZXY_______________|
| Month | Bet | Win |Payout|
|_______________|_______|______|______|
|Name|Group|Desc| | | |
|_______________|_______|______|______|
|Name|Group|Desc| | | |
|_______________|_______|______|______|
|_____Total_____|_______|______|______|
_____________________________________
|_____________Group ZXY_______________|
| Month | Bet | Win |Payout|
|_______________|_______|______|______|
|Name|Group|Desc| | | |
|_______________|_______|______|______|
|Name|Group|Desc| | | |
|_______________|_______|______|______|
|_____Total_____|_______|______|______|
如您所见,返回的数据具有相同的组,但被分开了。在这种情况下必须只使用 1 个表
我的想法总结
组循环 添加
<table><th>..</th></table>
变量内的标签
数据获取循环 添加
<tr><td>..</td></tr>
变量内的标签
这是代码
$sql='SELECT DISTINCT `groups` FROM `kiosk_data` WHERE `groups` IS NOT NULL ORDER BY `groups` ASC';
$grpData='';
$grpHr[]=array();
//this is the code I used to fill im th contents of the dropdown box
$result = $conn->query($sql);
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
if(!empty($row['groups']))
{
$selected = (isset($_GET['grp']) && $_GET['grp']==$row['groups'])?'selected="selected"':'';
$grpData.='<option value="'.$row['groups'].'"'.$selected.'>'.$row['groups'].'</option>';
$grpHr[]=$row['groups'];//took this opportunity to store the values of groups in grpHr[] Array
}
}
$sql = "SELECT COALESCE(kd.`kiosk_name`,'Total') AS 'Kiosk',
FORMAT(SUM(`casino_bets`),2) AS 'CBTotal', FORMAT(SUM(`bet_win`),2) AS 'BWTotal'
,FORMAT((`casino_bets`-`bet_win`)/`casino_bets`*100,2) AS 'Payout', groups FROM
`kiosk_data` kd LEFT JOIN `kiosk_status` ks ON kd.`kiosk_id`=ks.`kiosk_id` WHERE
`kiosk_name` IS NOT NULL AND `casino_bets` IS NOT NULL AND `bet_win` IS NOT NULL";
$result = $conn->prepare($sql);
$result ->execute();
foreach ($grpHr as $key => $value) {//iterate til the last group name
$key = $row['groups'];//I think I need to do this before entering the fetch loop
echo '<table><tr><td colspan="6">'.$row['groups'].'</td></tr><tr><th colspan="3">'.date("m",strtotime($row['date'])).'Month</th><th>Bet</th><th>Bet-Win</th><th>Payout %</th></tr>';
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
echo '<tr><td>'.$row['Kiosk'].'</td><td>'.$row['groups'].'</td><td>'.$row['city'].'</td><td>'.$row['CBTotal'].'</td><td>'.$row['BWTotal'].'</td><td>'.$row['Payout'].'</td></tr>';
}
}
除了我的想法之外,还有其他可能的解决方法吗?
【问题讨论】:
-
从我对您帖子的理解来看,我认为您有一个工作代码,但是
foreach块对我来说看起来很奇怪。真的给你想要的结果吗? -
另外,我查看了您链接的问题,如果您按
groups对查询进行排序并检查$row['groups']以了解while块开头的更改,那么答案应该有效.