我想在他们的“个人资料div”中为两个用户显示一些标题。
假设有五个标题属于用户1,只有两个标题属于用户2。
标题在我通过用户ID加入的表中。
我如何知道标题外键(用户ID)何时从一切换到二?换句话说,我该如何检查何时开始为新用户回显标题。
我想在进行切换时实现一个新的div,以便可以在其div中找到属于一个用户的标题,对于其他用户,依此类推
下面是我的查询,可以很好地显示我的数据。
为了简单起见,我使用了两个用户的示例,但是将来我将有两个以上的用户。
$result = mysqli_query($con,$sqltwo)or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo $row['user_id'];
//I want to echo a new div here when the user_id switches to new
value
//and then echo the new titles data for the new user_id.
echo "<br>";
}
编辑:成功的场景将是如下所示的输出:
<div class="userone">
title1<br>
title2<br>
title3<br>
title4<br>
title5<br>
</div>
<div class="usertwo">
title6<br>
title7<br>
</div>
答案 0 :(得分:0)
可以用基本算法完成:
$current_id = '';
while ($row = mysqli_fetch_array($result)) {
if ($current_id != $row['user_id']) {
//new user detected
$current_id = $row['user_id'];
}
}
因此,可以满足您的需求:
$current_id = '';
while ($row = mysqli_fetch_array($result)) {
if ($current_id != $row['user_id']) {
//ignore the first instance where no div has been created yet
if ($current_id != '') {
echo '</div>';
}
echo '<div class = "user'.$row['user_id'].'">';
$current_id = $row['user_id'];
}
//fill your div with your stuff from current user
echo $row['title'] . '<br>';
}
//check if you have at least one row to deal with, and then close the last opened div
echo '</div>';