0

我有一张桌子,上面有每天的信息:

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...
4

1 回答 1

0

GROUP_CONCAT()您可能会发现在 MySql 端使用它来打包和获取每天的详细信息很方便,以便explode()在渲染页面时在 php 端进一步

SELECT date, GROUP_CONCAT(CONCAT_WS('|', name, startHour, endHour) ORDER BY name) schedule
  FROM days
 GROUP BY date

样本输出:

+------------+------------------------------------ ------------+
| 日期 | 时间表 |
+------------+------------------------------------ ------------+
| 2013-05-01 | 约翰|12:00:00|16:00:00,马尔科|12:00:00|16:00:00 |
| 2013-05-02 | 约翰|12:00:00|17:00:00,彼得|12:00:00|17:00:00 |
| 2013-05-03 | 彼得|12:50:00|18:00:00 |
+------------+------------------------------------ ------------+

这是SQLFiddle演示


现在这里是如何使用 PDO 在 php 中处理它

<?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>

样本输出:

样本输出

于 2013-07-01T18:19:25.657 回答