我的SQL表中有以下数据:
id code day time year
1 PRC-001 0 t-1 2017
2 PRC-001 1 t-2 2017
3 PRC-002 0 t-3 2017
4 PRC-002 1 t-4 2017
5 PRC-003 0 t-5 2017
6 PRC-003 1 t-6 2017产出应如下:
day0 day1 code
t-1 t-2 PRC-001
t-3 t-4 PRC-002
t-5 t-6 PRC-003 我该怎么做?我在尝试下面的代码。但我没有得到任何欲望输出。这是我的代码:
$query1 = "SELECT * FROM routine AS tab1,";
$query1.= " GROUP BY code";
$rs = mysql_query($query1);
$numOfRows=mysql_num_rows($rs);
$printed = array();
$resultset = array();
while($row = mysql_fetch_assoc($rs)) {
$resultset[] = $row;
#print_r($row);
}
$q = "<table id='ash'>";
$q.= "<tr id='grey'>";
$q.= "<th rowspan='2'>day0</th>";
$q.= "<th rowspan='2'>day1(s)</th>";
$q.= "<th rowspan='2'>code</th></tr>";
$q.= "</tr>";
foreach ($resultset as $row){
$q.= "<tr>";
$q.= "<tr><td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>".$row["code"]."</td></tr>";
}
$q .= "</table>";
echo $q;发布于 2017-01-04 08:43:53
首先,正如注释中提到的,您应该考虑使用mysql_函数以外的其他东西。
其次,通过查询,您需要删除GROUP BY。
然后你就可以做这样的事情:
$rs = mysql_query("SELECT * FROM routine");
$results = [];
while ($row = mysql_fetch_assoc($rs)) {
$code = $row['code'];
if (!isset($results[$code])) {
$results[$code] = [
'day0' => '-',
'day1' => '-',
];
}
$results[$code]['day' . $row['day']] = $row['time'];
}
?>
<table>
<thead>
<tr id="grey">
<th rowspan="2">Day0</th>
<th rowspan="2">Day1(s)</th>
<th rowspan="2">code</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $code => $result) : ?>
<!--You shouldn't have multiple elements using the same ids-->
<tr>
<td id='clist'><?php echo $result['day0'] ?></td>
<td id='clist'><?php echo $result['day1'] ?></td>
<td id='clist'><?php echo $code ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>希望这能有所帮助!
发布于 2017-01-04 08:40:25
根据您想要的表,一行中的列不在数据库表中的一行中!因此,您不能只通过查询结果来构建表。
例如,t-1, t-2 and PRC-001不在数据库中的一行中。如果day0是t-1,那么day1将为空,反之亦然。
解决方案:
您必须将empty or zero中的一个days放在最后一个表中,这样才有意义,并且不需要groupby
$query1 = "SELECT * FROM routine AS tab1";
$rs = mysql_query($query1);
$numOfRows=mysql_num_rows($rs);
$printed = array();
$resultset = array();
while($row = mysql_fetch_assoc($rs)) {
$resultset[] = $row;
#print_r($row);
}
$q = "<table id='ash'>";
$q.= "<tr id='grey'>";
$q.= "<th rowspan='2'>day0</th>";
$q.= "<th rowspan='2'>day1(s)</th>";
$q.= "<th rowspan='2'>code</th></tr>";
$q.= "</tr>";
foreach ($resultset as $row){
if($row['day'] == 0){
$q.= "<tr>";
$q.= "<tr><td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>"EMPTY!"</td>";
$q.= "<td id='clist'>".$row["code"]."</td></tr>";
} else {
$q.= "<tr>";
$q.= "<tr><td id='clist'>"EMPTY!"</td>";
$q.= "<td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>".$row["code"]."</td></tr>";
}
}
$q .= "</table>";
echo $q;https://stackoverflow.com/questions/41458909
复制相似问题