0

所以我有这段代码组成了一个时间表网格(日期和时间),我连接到数据库并选择表,如你所见......我想做的是例如当英语课在星期一 0900 开始时,我想将此信息插入网格中,我该如何实现?非常感谢

<?php
error_reporting(E_ALL);
mysql_connect('db','user','password')
   or die(mysql_error());
mysql_select_db('db')
   or die(mysql_error());
$sql = "select day,start,class,time
  from event where class='english'";
$res = mysql_query($sql)
   or die(mysql_error());

   $days = array('Monday','Tuesday','Wednesday','Thursday','Friday');
$times= array('09','10','11','12','13','14','15','16');
echo "<table id='grid'>\n";
echo "<tr><td></td>";
for($t=0;$t<count($times);$t++)
  echo "<th>$times[$t]:00</th>";
echo "<tr>\n";
for($d=0;$d<count($days);$d++){
  print "<tr><th>$days[$d]</th>";
  for($t=0;$t<count($times);$t++)
    echo "<td id='td_$days[$d]_$times[$t]'></td>";
  echo "</tr>\n";
}
echo "</table>\n";
?>
4

1 回答 1

0

首先对你的数组使用 foreach()

   foreach($times as $time)
     echo "<th>$time:00</th>";

其次,尽量不要把 php 和 html 混为一谈。所有这些至少使您的代码更干净。对于 db 结果,您应该使用 mysql_fetch_array();

比这样走:

<table id='grid'>
    <tr>
        <td></td>
        <?php 
            foreach ($times as $time)
                echo "<th>$time:00</th>";
        ?>
    <tr>
        <?php 
            foreach ($days as $day){
                echo "<tr><th>$day</th>";
                foreach ($times as $time){
                    $english = ($day == $res['day'] && $time == $res['time']) ? $res['class'] : '';
                    echo "<td id='td_$day_$time'>{$class}</td>";
                }
            }
        ?>
    </tr>
    </table>
于 2012-04-11T13:28:42.657 回答