Close

Comments now displaying using brute force!

A project log for Hack-a-blog using the API

Turn project logs from a Hackaday.io project into a blog on your external website

Alex RichAlex Rich 07/15/2016 at 03:070 Comments

Some how, some way I figured out how to display the comments. It's a total butcher job of the code, a better programmer probably would have some elegant way to do this with recursion or something, instead I just used three for loops. But hey, it's working! Good example of comments displaying (even third tier level) is shown on this page:

http://www.stickvise.com/blog/2

Here is the new print_comments function I made to brute force the display of comments in the correct nested manner. I

// print_comments function
function print_comments($comments) {
  
  // loop through comments array
  echo '<ul>';
  foreach($comments as $comment_object1) {        
    // find and print first tier comments 
    if($comment_object1['reply_to'] == 0) {
      echo '
      <p><a href="'.$comment_object1['user']['url'].'" target="_blank">'.$comment_object1['user']['screen_name'].'</a><br />
      '.$comment_object1['comment'].'
      </p>';
      
      // loop through comments array again to find second tier comments
      echo '<ul>';
      foreach($comments as $comment_object2) {
        // find and print second tier comments replying to the above tier comment
        if($comment_object2['reply_to'] == $comment_object1['id']) {
          echo '
          <p><a href="'.$comment_object2['user']['url'].'" target="_blank">'.$comment_object2['user']['screen_name'].'</a><br />
          '.$comment_object2['comment'].'
          </p>';
          
          // loop through comments array third time to find third tier comments
          echo '<ul>';
          foreach($comments as $comment_object3) {
            // find and print third tier comments replying to the second tier comment
            if($comment_object3['reply_to'] == $comment_object2['id']) {
              echo '
              <p><a href="'.$comment_object3['user']['url'].'" target="_blank">'.$comment_object3['user']['screen_name'].'</a><br />
              '.$comment_object3['comment'].'
              </p>';
            }
          }
          echo '</ul>'; // end third tier comments
        }
      }
      echo '</ul>'; // end second tier comments
    }
  }
  echo '</ul>'; // end first tier comments
} // end print_comments()

Discussions