我每天都有一张信息表:
idDya | date | startHour | endHour | totalHours | name
-------------------------------------------------------
1 05/01 12:00 16:00 4 John
2 05/01 12:00 16:00 4 Marko
3 05/02 12:00 17:00 3 John
4 05/02 12:00 17:00 3 Peter
5 05/03 12:50 18:00 5 Peter
我有一张动态表:
<?php
$sql = " SELECT * FROM days ";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo "<table width='435' border='1' cborder='1' cellpadding='2' cellspacing='0' bordercolor='#666666' class='boldtable'>
<tr>
<td>".$row['idDya']."</td>
<td>".$row['date ']."</td>
<td>".$row['totalHours']."</td>
<td>".$row['name']."</td>
</tr>
</table>";
}
?>
问题:“我如何格式化表格,因此我有一个动态表格,但每个单元格都适合该日期的信息”。
day schedule
--------------------------------
05/01 | John 12:00 -16:00
Marko 12:00 -16:00
--------------------------------
05/02 | John 12:00 -16:00
Peter 12:00 -16:00
--------------------------------
etc...
答案 0 :(得分:0)
您可能会觉得在MySql端使用GROUP_CONCAT()
方便一天打包并获取详细信息,以便在渲染页面时在php端进一步explode()
SELECT date, GROUP_CONCAT(CONCAT_WS('|', name, startHour, endHour) ORDER BY name) schedule
FROM days
GROUP BY date
示例输出:
+------------+------------------------------------------------+ | date | schedule | +------------+------------------------------------------------+ | 2013-05-01 | John|12:00:00|16:00:00,Marko|12:00:00|16:00:00 | | 2013-05-02 | John|12:00:00|17:00:00,Peter|12:00:00|17:00:00 | | 2013-05-03 | Peter|12:50:00|18:00:00 | +------------+------------------------------------------------+
这是 SQLFiddle 演示
现在,您可以在php中使用PDO处理它
<?php
$db = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT date, GROUP_CONCAT(CONCAT_WS('|', name, startHour, endHour) ORDER BY name) schedule
FROM days
GROUP BY date";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetchall(PDO::FETCH_ASSOC);
$query = null;
$db = null;
?>
<table width='435' border='1' cborder='1' cellpadding='2' cellspacing='0' bordercolor='#666666' class='boldtable'>
<thead>
<tr>
<th>Day</th>
<th>Schedule</th>
</tr>
</thead>
<tbody>
<?php
foreach($rows as $row) {
echo "<tr>
<td>{$row['date']}</td><td>";
$schedule = explode(',', $row['schedule']);
foreach($schedule as $details) {
list($name, $start_hour, $end_hour) = explode('|', $details);
echo "$name $start_hour-$end_hour<br>";
}
echo "</td></tr>";
}
?>
</tbody>
</table>
示例输出: