0

Ok, so I have loop which has 6 items (comments) as shown below.

  • User1 Comment
  • User2 Comment
  • User1 Comment
  • User1 Comment
  • User3 Comment
  • User4 Comment

If I put limit for 4 comment this is what I get

  • User1 Comment
  • User2 Comment
  • User1 Comment
  • User1 Comment

But instead of that I want to be able to eliminate same user comments and instead show others. It should look like that.

  • User1 Comment
  • User2 Comment
  • User3 Comment
  • User4 Comment

How can I achieve this ?

    foreach($latestcomments as $comment){

    echo $comment->content;

    }
4
  • do you want to show the most recent comment for each user? Commented Jul 10, 2013 at 17:26
  • Not possible with only one loop. You need at least two: one to find out what kind of comments you have and then one to output them. Commented Jul 10, 2013 at 17:29
  • @user20... if this is desired, not the loop is incorrect, but the way of fetching the data. Commented Jul 10, 2013 at 17:31
  • can you post your sql? Commented Jul 10, 2013 at 17:32

2 Answers 2

3
$shown = array();

foreach($latestcomments as $comment) {
  if(!isset($shown[$comment->user])) {
     $shown[$comment->user] = true;
     echo $comment->content;
  }
}

If the user hasn't been "shown" before, the comment will be shown. if they have, the comment will simply get skipped.

Sign up to request clarification or add additional context in comments.

1 Comment

plus a $limit++ and $limit<=4
0

Id do it like this...

$user = ""; $i=0;

foreach($latestcomments as $comment) {
 if($i<=4){
   if($comment->user!=$user){
    echo $comment->content;
    $user = $comment->user;
    $i++;} else { $user = $comment->user;}
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.