我正在用php编写一个网页,以从mySQL数据库中检索玩家详细信息并将其写入div中的正文,例如:
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
我想做的是一次将其中三个放入一个div 中,这样当从数据库中检索到另外两个时,它将结束包含的div 并为接下来的三个开始一个新的div,如下所示:
<div class="container">
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
</div>
.我用来将数据写入文档的 php 在这里:
$con = mysqli_connect($servername, $username, $password, $dbname);
$sql="SELECT PlayerName,PlayerUID,PlayerMorality,PlayerSex FROM player_data";
if ($result=mysqli_query($con,$sql)){
while ($row=mysqli_fetch_row($result)){
echo "<div class="infoDiv">";
echo "<img style="margin: 10px; float:left" src="epoch.png"/>";
echo "<p>Player Name: " . $row[0] . "</p>";
echo "<p>Player ID: " . $row[1] . "</p>";
echo "<p>Player Morality: " . $row[2] . "</p>";
if($row[3]=="0"){
echo "<p>Gender: Male</p>";
}
else{
echo "<p>Gender: Female</p>";
}
echo "</div><br>";
}
mysqli_free_result($result);
}
对于这个问题,我提前道歉,我知道它的措辞很差,如果你不明白我在问什么,请随时问。谢谢。
只需保留一个计数器:
$rows_output = 0;
while(... fetch from db ...) {
if ($rows_output % 3 == 0) {
... start a new container ...
}
... output row data
if ($rows_output % 3 == 2) {
... just output the 3rd row, end the container ...
}
$rows_output++;
}
最简单的解决方案是将某种索引计数器放入循环中,当它可以除以 3 时,您可以关闭当前的div 并开始新的:
$con = mysqli_connect($servername, $username, $password, $dbname);
$sql="SELECT PlayerName,PlayerUID,PlayerMorality,PlayerSex FROM player_data";
$resultIndex = 1;
if ($result=mysqli_query($con,$sql)){
while ($row=mysqli_fetch_row($result)){
echo "<div class="infoDiv">";
echo "<img style="margin: 10px; float:left" src="epoch.png"/>";
echo "<p>Player Name: " . $row[0] . "</p>";
echo "<p>Player ID: " . $row[1] . "</p>";
echo "<p>Player Morality: " . $row[2] . "</p>";
if($row[3]=="0"){
echo "<p>Gender: Male</p>";
}
else{
echo "<p>Gender: Female</p>";
}
echo "</div><br>";
if ($resultIndex % 3 == 0) {
echo "</div><div class="container">";
}
$resultIndex++;
}
mysqli_free_result($result);
}
您可以使用array_chunk($array , how many per each)
并将其放在foreach
循环中,例如
foreach (array_chunk($array , 3) as $row)
{
foreach ($row as $item)
{
the html goes here
}
// now 3 items has passed ,add something b4 the next 3
}