Search code examples
phpcodeignitersimplepie

Show each date only once


All right, this must be an absolutely easy question, and I apologize for that.

I also apologize if I simply failed in finding the right search terms to use to come to an answer on my own. I did try, but my lack of fluency in PHP kind of makes me suck at searching.

I'm looking for a simple way to show each date only once within a foreach loop. I'm looping through data like so:

<?php
  echo "<ul>";
  foreach($rss_items as $i){
   if($i->get_feed()->get_title() == 'Twitter (no @ replies)'){
   echo "<li>";
   echo $i->get_date();
   echo "<a href='" .$i->get_link()."'>Twitter</a>";
   echo $i->get_title();
   echo "</li>";
   }
   elseif($i->get_feed()->get_title() == 'Pinboard (jpcody)'){
   echo "<li>";
   echo $i->get_date();
   echo "<a href='" .$i->get_link()."'>Pinboard</a>";
   echo $i->get_title();
   echo "</li>";
   }
   elseif($i->get_feed()->get_title() == 'Entries at Church Marketing Sucks by Joshua Cody'){
   echo "<li>";
   echo $i->get_date();
   echo "<a href='" .$i->get_link()."'>Church Marketing Sucks</a>";
   echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
   echo $i->get_description();
   echo "</li>";
   }
   elseif($i->get_feed()->get_title() == 'Flickr remove first paragraph'){
   echo "<li>";
   echo $i->get_date();
   echo "<a href='" .$i->get_link()."'>Flickr</a>";
   echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
   echo $i->get_description();
   echo "</li>";
   }
  }
  echo "</ul>";
 ?>

And each item contains the date, so I'm getting the same date multiple times. I'd like to only have each date shown once, a la http://daringfireball.net.

I'm using CodeIgniter and the SimplePie library, so all of the data is being pulled directly instead of being stored in a db. I imagine a way to do it could be including a second if statement to check if the date has already been used, but I don't know how to execute this.

I'm pretty new to PHP, and I'm really looking to learn more than just have a solution given.

Any help you could give would be great!


Solution

  • You need to remember what was the date you used last, and print it only if it differs. You can try something like:

    $previous_date = null;
    foreach ($rss_items as $item) {
        if ($item->get_date() != $previous_date) {
            $previous_date = $item->get_date();
            echo '<li>' . $previous_date . '</li>';
        }
        ...
    }
    

    (And don't forget to HTML-encode the titles and links using htmlspecialchars.)