PHP to check for duplicate sequential values
I am displaying some data in PHP and I'm looking for logic to check for duplicate values, but only sequential duplicate values.
For example, right now I have this showing up for a list of music played at a concert:
Beethoven Ninth Symphony
- Pa开发者_StackOverflow中文版rt 1Beethoven Ninth Symphony
- Part 2Mahler Symphony
- Part 1Beethoven Ninth Symphony
- Part 4Instead I'd like it to read like this - so that I don't repeat the title IF it matches the title of the previous item. But if it's not the same as the item before it, it would display the title again.
Beethoven Ninth Symphony
- Part 1 - Part 2Mahler Symphony
- Part 1Beethoven Ninth Symphony
- Part 4Thanks for any help!
Suppose you have a list of symphony objects, $musicList. Each item has title and part number properties.
$previousTitle = 0;
foreach ($musicList as $item) {
if ($item->title != $previousTitle) {
print $item->title;
}
print "- " . $item->partNumber;
$previousTitle = $item->title;
}
You just need to store the last concert name you printed in some variable, so that you can compare it to the current concert name as you print out each one. When they are equal, don't print anything, when they're not, update the variable and print the new concert name.
while ($row = mysql_fetch_array($result_resource)) {
if (!isset($last) || $last != $row['concert_name']) {
$last = $row['concert_name'];
echo "<h1>" . $row['concert_name'] . "</h1>";
}
echo $row['song_name'] . "<br />";
}
精彩评论