PHP的foreach数组输出到表空单元格

我想为自己做一个简单的教学计划,并卡住我的数组的输出。PHP的foreach数组输出到表空单元格

这里的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>&nbsp</td>

<td>&nbsp</td>

<td>&nbsp</td>

<td>&nbsp</td>

<td>m5 ict</td>

<td>&nbsp</td>

<td>m6 ict</td>

<td>&nbsp</td>

</tr>

我想过的foreach使用if语句,但我想不通,我需要做什么样的关系。

任何援助将不胜感激。

回答:

试试这个

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

回答:

由于您使用的数字键,你知道有一个星期只有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

}

}

以上是 PHP的foreach数组输出到表空单元格 的全部内容, 来源链接: utcz.com/qa/257219.html

回到顶部