I’m trying to dynamically create 5 divs that represent 5 days of the week. In each div, I’m trying to loop through data fetched from my code igniter model and echo a series of un-ordered list based upon a project, a date, and tasks that are related to that project. I’m fetching the data from both my project table, to echo the project name in h4 tags, and from the task table, to echo related task under the project h4. The problem I’m having is that I can’t seem to find a way to prevent my algorithm from repeating project names and related tasks. In other words, if there’s two tasks related to one project, that project and the two related tasks will be echoed out twice. Here’s an image to help explain the problem:

<?php for($counter = 0; $counter < 5; $counter++): ?><!-- loops through and creates divs -->
<?php
$date = date("F j, Y");
$refDate = date("Y-m-d");
$counterForLi = 0;
?>
<div class="span2 check-list date-container">
<div id="form-to-date">
<div class="replace">
<h2 class="day"></h2>
<h4 class="thedate">
<?php
if ($counter > 0) {
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+$counter, date("y"));
$refDate = date("Y-m-d", $tomorrow);
$date = date("F j, Y", $tomorrow);
echo $date;
} else {
echo $date;
}
?>
</h4>
<input type="hidden" name="thedate" class="hidden-date" value="<?php echo $refDate; ?>">
<?php if(isset($tasks)) : foreach($tasks as $taskRow) :?> <!-- loop through the tasks -->
<?php if($taskRow->dateadded == $refDate) : ?> <!-- in the context of the right date -->
<?php if(isset($taskRow->_project_fk)) : ?>
<?php
$relatedProjectId = $taskRow->_project_fk;
$relatedProjectName = NULL;
if(!isset($relatedProjectName)) {
foreach ($projects as $ProjectRow) {
if ($ProjectRow->__project_pk == $relatedProjectId) {
$relatedProjectName = $ProjectRow->project_name;
echo "<h4>" . $relatedProjectName . "</h4>";
echo "<ul>";
}
}
foreach ($tasks as $task) {
if ($task->_project_fk == $relatedProjectId && $task->dateadded == $refDate) {
echo "<li>".$task->task_name."</li>";
}
}
echo "</ul>";
}
?>
<?php endif; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div><!-- /replace -->
</div><!-- /form-to-date -->
</div>
<?php endfor; ?>
I realize this code is kind of a mess so if you need clarification, please ask.
Edit:
Here’s the structure of my tasks array

Start by creating a hierarchical array structure that groups tasks by project and date. From your example and data structure it looks like each task belongs to one project and was started on one date. For each date, you want to show each project that had at least one task that started on that date along with those tasks that started on that date.
Next create a map from project ID (PK) to the project. This makes looking up each project’s name faster since you loop over all projects only once.
Finally, you’re ready to build your UI. I’ll leave fitting it into HTML up to you and just output a simple text view. The logical flow will be identical.