简体   繁体   中英

How to populate an html table with data from an array in php

I am new in php and I have problem to solve one task.

I have to create empty table for the school schedule for 7 hours (with the duration in 1 line) for Monday - Friday, 1 hour lasts 45 minutes (15 minute break, 2 break is 20 minutes, 5 break is 30 minutes).

I wrote this, but I don't know how to proceed.Can you please help me with this?

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html">
<title>Task1</title>
</head>
<body>            
<?php
header("Content-Type: text/html; charset=windows-1250");
$days = array('Monday', 'Tuesday', 'Wednesday', 'Thurstday', 'Friday');
$times = array('08:00-08:45','09:00-09:45','10:05-10:50','11:05-11:50','12:05-12:50','13:20-14:05','14:20-15:05');
$rows = 5;
$columns = 7;
$i = 0;
$j = 0;

echo "<table border='1'>";
for ($i = 1; $i <= rows; $i++)
{
    echo("<tr>");
    for ($j = 1; $j <= columns; $j++)
        echo "<td>$days[$i]</td>";
    $i += 1;
    echo("</tr>");
}
echo("</table>");

You have several problems.

  1. Array indexes start at 0 , not 1 . But it's usually clearer to use foreach .
  2. You shouldn't hard-code the array lengths, use count() .
  3. You're missing several $ before variable names.
  4. You're not printing the times from $times . They should be printed as a header line before the first day.
  5. You shouldn't have $i = $i + 1; , as you'll increment $i twice because of $i++ .
$days = array('Monday', 'Tuesday', 'Wednesday', 'Thurstday', 'Friday');
$times = array('08:00-08:45','09:00-09:45','10:05-10:50','11:05-11:50','12:05-12:50','13:20-14:05','14:20-15:05');
$columns = count($times);

echo "<table border='1'>";
echo "<tr><th>Day</th>;";
foreach ($times as $time) {
    echo "<th>$time</th>";
}
echo "</tr>";
foreach ($days as $day) {
    echo("<tr><th>$day</th>");
    for ($i = 0; $i < $columns; $i++) {
        echo "<td></td>"; // empty fields for each period
    }
}
echo "</tr>";
echo("</table>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM