我想使用PHP顯示格式化的HTML時間表。如何將PHP數據的多維數組轉換爲HTML表格?
我想將數據從多維數組輸出到格式爲總共8列的HTML表格中(每天的列爲Mon-Sun,左邊爲顯示每個會話的開始時間的列)。 行數取決於每天有多少會話。
我的解決方案在某種程度上可行,您可以在下圖中看到輸出,但您也可以看到由於某種原因生成了額外的行。無論一天的會話數量如何,總是隻有一行。
的數據是這樣表示:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 1
[name] => A Monday Session
[start_time] => 10:00
)
[1] => Array
(
[id] => 5
[name] => Another Monday Session
[start_time] => 11:00
)
[2] => Array
(
[id] => 6
[name] => Yet Another Monday Session
[start_time] => 12:00
)
)
[1] => Array
(
[0] => Array
(
)
)
[2] => Array
(
[0] => Array
(
[id] => 8
[name] => A Wednesday Session
[start_time] => 14:30
)
)
[3] => Array
(
[0] => Array
(
[id] => 3
[name] => A Thursday Session
[start_time] => 09:00
)
)
[4] => Array
(
[0] => Array
(
)
)
[5] => Array
(
[0] => Array
(
)
)
[6] => Array
(
[0] => Array
(
[id] => 4
[name] => A Sunday Session
[start_time] => 13:00
)
)
)
正如你所看到的主鍵表示一週的日子。 0 =星期一,1 =星期二等。 每天有一個會話列表。在這個例子中,星期一有3個會話,週三,週四,週日也有一個。
請注意,它們都有不同的起始時間。將會話引入具有重複開始時間的數據的那一刻,也會創建額外的行,而不是共享同一行。週四會議的輸出改爲10:00,與星期一相同:
這裏是我的越野車解決方案。我在評論中標出了我要出錯的地方。
// $sessionRows is the array of arrays containing the data above.
// Grabs array of session times from $sessionRows that has been sorted and duplicates removed.
// Current values: Array ([0] => 09:00 [1] => 10:00 [2] => 11:00 [3] => 12:00 [4] => 13:00 [5] => 14:30)
$sessionTimes = $this->getSessionTimes($days);
$numOfRows = count($sessionTimes);
$numOfCols = $dayIdx;
// Create grid with correct dimensions and rows represented by the session times
$grid = array();
for($i=0;$i<count($sessionTimes);$i++) {
$row = array();
for($j=0;$j<$numOfCols;$j++) {
$row[] = '<td></td>';
}
$grid[$sessionTimes[$i]] = $row;
}
// Populate grid with session info added to correct coordinates.
for($i=0;$i<$numOfCols;$i++) {
echo count($sessionRows[$i]);
for($j=0;$j<count($sessionRows);$j++) {
$grid[$sessionRows[$i][$j]['start_time']][$i] = $sessionRows[$i][$j];
}
}
$rows='';
$idx = 0;
foreach($grid as $rowArray) {
$rows .= '<tr>';
/*** This lines is the problem! It adds the session time as the first column. ***/
$rows .= '<td class="time-col">'.$sessionTimes[$idx].'</td>';
for($i=0;$i<count($rowArray);$i++) {
if(!empty($rowArray[$i]['name'])){
$rows .= '<td>'.$rowArray[$i]['name'].'<br>'.$rowArray[$i]['start_time'].'</td>';
} else {
$rows .= '<td> - </td>';
}
}
$rows .= '</tr>';
$idx++;
}
return $rows;
你怎麼知道一個星期的一天? – Misunderstood
只是因爲陣列的排列方式。 0 =星期一,1 =星期二等 – Muzzstick