开发者

PHP to check for duplicate sequential values

开发者 https://www.devze.com 2023-01-29 13:57 出处:网络
I am displaying some data in PHP and I\'m looking for logic to check for duplicate values, but only sequential duplicate 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 1

Beethoven Ninth Symphony

- Part 2

Mahler Symphony

- Part 1

Beethoven Ninth Symphony

- Part 4

Instead 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 2

Mahler Symphony

- Part 1

Beethoven Ninth Symphony

- Part 4

Thanks 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 />";

}
0

精彩评论

暂无评论...
验证码 换一张
取 消