Hello all,
This is a problem I have run into before and I have yet to find an elegant solution, so I thought I would ask for SO's help.
I am iterating through an array and printing off some information from that array and having trouble figuring out how to print my start and end <div>
tags. Below is an example table and the desired output along with a basic implementation of my current algorithm. I am hoping that somebody can point me to a better algorithm for printing the data. I'm doing it in PHP, but a generic algorithm would be wonderful.
Thanks very much!
Table: (spacing added for clarity)
Choice ID Choice Body Question ID Question Body --------------------------------------------------------------------- 1 Yes, very much 1 Do you like sandwiches? 2 Somewhat 1 Do you like sandwiches? 3 Not at all 1 Do you like sandwiches? 4 I hate them 1 Do you like sandwiches? 5 Sure, why not 2 Do you like apples? 6 Yesh, I guess 2 Do you like apples? 7 What are those 2 Do you like apples? 8 Yes, very much 3 Do you like chips? 9 Not at all 3 Do you like chips?
Desired Output:
<div class='question' id='1'>
<p>Do you like sandwiches?</p>
<div class='choices'>
<span class='choice'>Yes, very much</span>
<span class='choice'>Somewhat</span>
<span class='choice'>Not at all</span>
<span class='choice'>I hate them</span>
</div>
</div>
<div class='question' id='2'>
<p>Do you like apples?</p>
<div class='choices'>
<span class='choice'>Sure, why not</span>
<span class='choice'>Yeah, I guess</span>
<span class='choice'>What are those</span>
</div>
</div>
<div class='question' id='3'>
<p>Do you like chips?</p>
<div class='choices'>
<span class='choice'>Yes, very much</span>
<span class='choice'>Not at all</span>
</div>
</div>
Basic Algorithm I'm Currently Using:
$last_id = null;
while ($choice = pg_fetch_array($choices)) {
if ($last_id != $choice['id']) {
if ($last_id != null) {
echo "</div>";
}
echo "<div id='$choice[id]'>";
}
// Print choice info
$last_id = $choice['id'];
}
if ($last_id != null) {
echo "</div>";
}
Note: The reason I'm using this way is for optimization purposes. This requires only one database query, and there are going to be a lot of results. I don't want to have to do a query for each question to get it's choices. I know how to do that, and it is easier, but not very efficient or fast.
Edit 1: Fixed code, the algorithm now works, but still isn't pretty. For the commenter: pg_fetch_array()
is a PostgreSQL function that basically creates an associative array. Very similar to an object. Allows you to just ask for the $choice['id']
or $choice['body']
.