Placing data into 'one-per-day' cells in a PHP-generated calendar
I have a calendar which I need to populate with data drawn from a MySQL database.
The query response will be an array of rows referring to several dates in a month. I have to get each row's data into the that corresponds to its date. The date info is stored as 'datetime' in MySQL.
The calendar elements that will hold the data are generated here:
for ($day = 1; $day <= $totaldays; $day++) {
$day_secs = mktime(0,0,0,$month,$day,$year);
if ($day_secs >= $yesterday) {
if ($day_highlight && ($day == $this_day)) {
print "<td class=\"today\"><span>$day</span><a href=\"CPD_activity_cal_new.php?day=$day&month=$month&year=$year\" class=\"actilink\">Add Activity</a>
</td>";
} else {
print "<td class=\"monthday\"><span>$day</span><a href=\"CPD_activity_cal_new.php?day=$day&month=$month&year=$year\" class=\"actilink\">Add Activity</a></td>";
}
} else {
print "<td class=\"monthday\"><span>$day</span><a href=\"CPD_activity_cal_new.php?day=$day&month=$month&year=$year\" class=\"actilink\">Add Activity</a></td>";
}
$day_offset++;
// start a new row each week //
if ($day_offset == 7) {
$day_offset = 0;
if ($day < $totaldays) { print "</tr>\n<tr>"; }
}
}
I have three main headache开发者_如何学Cs here:
- can I use the output from mysql_fetch_array as-is - in other words, can I run a certain way through the array in one cell, and then restart the loop at the correct point a few cells later - or must I split it into separate arrays for each date (most dates in any month will typically be empty) - and if so, how?
- where in the code that generates the day-cells does my code for this belong? I'm particularly confused in this respect by the separate loops for today, pre-today, and post-today
- which form of loop would be best: I've been assuming while(), but I haven't been able to make it work (unsurprisingly, given the confusion above!).
I'ld be very grateful for any advice on this.
I'm not quite sure what the data looks like and your logic is a little spotty for me to fully understand, but this is basically how I see this working:
$result = mysql_query("SELECT *, DAY('date') AS day FROM table WHERE ... yadda, yadda");
// Reorganize the events into an array keyed by day of the month
$events = array();
while ($row = mysql_fetch_array($result)) {
if (!$events[$row['day']]) $events[$row['day']] = array();
$events[$row['day']][] = $row;
}
// Build calendar
for ($day = 1; $day <= $totaldays; $day++) {
// logic for outputting standard calendar format
if ($events[$day]) {
foreach ($events[$day] AS $row) {
// output events
}
}
}
精彩评论