Find change of title in while ($row = mysql_fetch_array($result)) { PHP
while ($row = mysql_fetch_array($result)) {
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>
Here's my working code. I want to attempt to find when $row['ideaTitle'] is new, but I'm not sure how to do it. I thought about setting a temp variable w/ the title name, but I feel like there needs to 开发者_运维技巧be a simpler solution.
Using a temporary variable is pretty much the way to go, I would say -- that's what I do in this kind of situation.
And it generally translates to this kind of code :
$previousTitle = null;
while ($row = mysql_fetch_array($result)) {
if ($row['ideaTitle'] != $previousTitle) {
// do something when the current line
// is the first with the current title
}
// work with $row
// Store the current title to the temporary variable,
// to be able to do the comparison on next iteration
$previousTitle = $row['ideaTitle'];
}
There is no other way than to use a temporary variable. But instead of using a single last value string, try a count map:
if (@$seen_titles[ $row["ideaTitle"] ]++ == 0) {
print "new title";
}
This trick works, because the counting up ++
is in effect done after the comparison. It needs an @
error suppression however for the redundant notices here.
Imo this is quite a simple solution. However, you could also preprocess the data and create a title => feedbacks
map:
$feedbacks = array();
while (($row = mysql_fetch_array($result))) {
if(!array_key_exists($row['ideaTitle'], $feedbacks) {
$feedbacks[$row['ideaTitle']] = array();
}
$feedbacks[$row['ideaTitle']][] = $row['feedback'];
}
And then create the output:
<?php foreach($feedbacks as $title => $fbs): ?>
<h3> <?php echo $title; ?> </h3>
<?php foreach($fbs as $fb): ?>
<blockquote>
<p>
<em><?php echo $fb ?></em>
</p>
</blockquote>
<?php endforeach; ?>
<?php endforeach; ?>
Keep a track of previously encountered titles in a key value array.
$prevTitles = array();
while ($row = mysql_fetch_array($result)) {
if($prevTitles[$row['ideaTitle']] == true)
continue;
$prevTitles[$row['ideaTitle']] = true;
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>
精彩评论