我正在尝试为自己制定一个简单的教学计划,并且我仍然坚持我阵列的输出。
这是PHP:
echo '<table><thead><tr><th>Period</th><th>1</th><th>2</th><th>3</th>th>4</th><th>5</th><th>6</th><th>7</th><th>8</th><th>9</th></tr>';
echo '<tr><th>Time</th><th>08:50</th><th>09:40</th><th>10:30</th><th>11:20</th><th>12:10</th><th>13:00</th><th>13:50</th><th>14:40</th><th>13:30</th></tr>';
echo '</thead><tbody>';
$results = $db->mysql->query("SELECT * FROM schedule");
if ($results->num_rows) {
while ($row = $results->fetch_assoc()) {
$days[$row['day']][$row['period']] = $row['classroom'];
} // close days while
foreach ($days as $key => $val) {
echo '<tr><td>' . $key .
'</td>';
foreach ($val as $item) {
echo '<td>' . $item .
'</td>';
}
echo '</tr>';
}
}
echo '</tbody></table>';
这给了我一个这样的数组:
Array
(
[Monday] => Array
(
[1] => m5 biology
[6] => m5 ict
[8] => m6 ict
)
[Tuesday] => Array
(
[3] => m5 biology
[6] => m6 ict
[7] => m6 ict
)
[Wednesday] => Array
(
[1] => m6 biology
[2] => m5 ict
[7] => m5 biology
[8] => m2 ict
)
[Thursday] => Array
(
[1] => m6 biology
)
[Friday] => Array
(
[1] => m6 biology
[6] => m6 ict
)
表输出如下所示:
...
<tr>
<td>Monday</td>
<td>m5 biology</td>
<td>m5 ict</td>
<td>m6 ict</td>
</tr>
...
我想要的是输出在空闲时段包含空表格单元格。在星期一的例子中,只有第1,6,8期的数据,所以它只显示那些单元格。
如何让这段代码输出2,3,4,5,7,9期间的空单元?像这样:
...
<tr>
<td>Monday</td>
<td>m5 biology</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td>m5 ict</td>
<td> </td>
<td>m6 ict</td>
<td> </td>
</tr>
我考虑在foreach中使用if语句,但我无法弄清楚我需要建立什么样的关系。
非常感谢任何协助。
答案 0 :(得分:3)
由于你使用的是数字键,并且你知道一周只有7天,所以不要使用foreach(),而是使用for()代替:
for($i = 1; $i <= 7; $i++) {
if(isset($array[$i])) {
... there's info for this day, output it
} else {
... no info, output a blank cell
}
}
答案 1 :(得分:2)
试试这个
<?php
$data = array (
"Monday" => Array
(
1 => "m5 biology",
6 => "m5 ict",
8 => "m6 ict",
),
"Tuesday" => Array
(
3 => "m5 biology",
6 => "m6 ict",
7 => "m6 ict",
),
"Wednesday" => Array
(
1 => "m6 biology",
2 => "m5 ict",
7 => "m5 biology",
8 => "m2 ict",
),
"Thursday" => Array
(
1 => "m6 biology",
),
"Friday" => Array
(
1 => "m6 biology",
6 => "m6 ict",
)
);
$table = "<table border = '1'><tr><td>Day</td>";
for ($x = 1; $x<8; $x++) {
$table .= "<td>Period $x</td>";
}
$table .= "</tr>";
foreach ($data as $day => $classes) {
$table .= "<tr><td>$day</td>";
for ($x = 1; $x<8; $x++) {
if (isset($classes[$x])) {
$table .= "<td>" . $classes[$x] . "</td>";
} else {
$table .= "<td></td>";
}
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;