如何在 while 循环中对元素进行排序


How do I sort elements in a while loop?

我即将在页面上显示评论,一切正常,但我想先显示用户的评论。那么,如何首先显示来自user_id的用户评论呢?我正在使用 while 循环来显示评论。

如果有人能帮助我,我将不胜感激。 :)

                <?php
                    $sql = "SELECT * FROM `comments` WHERE `post_id`=$pid AND `active`=1 ORDER BY ups-downs DESC";
                    $result = $mysqli->query($sql);
                    $count = $result->num_rows;
                    if($count == 1){
                        $counttext = "1 Comment";
                    }else{
                        $counttext = $count ." Comments";
                    }
                ?>
                <div class="media-area media-area-small">
                    <h3 class="text-center"><?php echo $counttext; ?></h3>
                <?php
                    while($row = $result->fetch_assoc()){
                        $uid = (int)$row["user_id"];
                        $user = get_user_info($mysqli,$uid);
                ?>
                    <div class="media">
                        <a class="pull-left" href="#">
                            <div class="avatar">
                                <img class="media-object" src="<?php echo $user["picture"]; ?>" alt="...">
                            </div>
                        </a>
                        <div class="media-body">
                            <table width="100%">
                                <tr valign="middle">
                                    <td align="left"><h4 class="media-heading text-left"><?php echo fb_clear_name($mysqli, $user["id"]); ?></h4></td>
                                    <td align="right"><h6 class="pull-right text-muted"><?php echo $row["ups"] - $row["downs"]; ?> bits</h6></td>
                                </tr>
                            </table>
                            <p><?php echo htmlentities($row["content"]); ?></p>
                            <div class="media-footer">
                                <a href="#" class="btn btn-info btn-simple "> <i class="fa fa-reply"></i> Reply</a>
                                <a href="#" class="pull-right text-muted">
                                    <?php echo $row["timestamp"]; ?>
                                </a>
                            </div>    
                        </div>
                    </div>
                <?php
                    }
                ?>

问候

您可以预筛选数据。例如使用

$user_comments=array();
$other_comments=array();
while($row = mysql_fetch_assoc($result))
{
    if($row['user']==$current_user)
   {
        $user_comments[]=$row;
   }
   else
  {
        $other_comments[]=$row;
  }
}
$comments=array_merge($user_comments,$other_comments);

然后,您可以按所需的方式显示信息。