如果我正确理解您的要求,您需要一个图像网格。网格是一个 2 条目表,因此您确实需要有 2 个循环。行的每个条目(即每一列)都来自第一个循环,每一行都来自第二个循环,调用内部的第一个循环。
我将继续下一个片段。但是,您没有给出一些未知的限制,因此我将假设其中一些。例如,我将假设您的数据作为一维数组返回。
<?php
$data = array('one', 'two', 'three', 'four', 'five', 'six');
$nbColumns = 3;
?>
<table>
<?php
for($row = 0; $row * $nbColumns < count($data); ++$row) {
?>
<tr>
<?php
for($col = 0; $col < $nbColumns; ++$col) {
?>
<td><?php echo $data[$row * $nbColumns + $col]; ?></td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
这将产生:
<table>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
<tr>
<td>four</td>
<td>five</td>
<td>six</td>
</tr>
</table>
您应该能够根据您的需要调整此代码段。
如果有什么需要我解释的,请告诉我,以便我可以编辑我的答案/片段。
编辑:
我不确定你需要我解释什么。
无论如何,我只是在我的代码片段中重新注入了您的初始代码,但我没有做任何特别的事情。基本上,我只是在顶部插入include
和调用,并用你的两行替换了哑数字,第一行是图像,第二个是链接/名称。executeSelectQuery
这应该可以正常工作,但我不能保证它会因为我没有你的代码的所有细节。
<?php
include 'dbFunctions.php';
$arrStocks = executeSelectQuery("SELECT name,id,image,price FROM stocks");
$nbColumns = 3;
?>
<table>
<?php
for($row = 0; $row * $nbColumns < count($arrStocks); ++$row) {
?>
<tr>
<?php
for($col = 0; $col < $nbColumns; ++$col) {
$index = $row * $nbColumns + $col;
$name = $arrStocks[$index]['name'];
$image = $arrStocks[$index]['image'];
$id = $arrStocks[$index]['id'];
$price = $arrStocks[$index]['price'];
?>
<td>
<img src="stocks/<?php echo $image; ?>" alt="<?php echo $name; ?>">
<br>
<a href="stockDetails.php?id=<?php echo $id; ?>"><?php echo $name; ?></a>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
作为结论,请注意您不应该使用 atable
来实现您想要的。我的回答有点骇人听闻(这$nbColumns
不是很好),但没有什么更好的方法可以使用table
s. 虽然使用float
s 可能是一个更好的解决方案,但它不再是 PHP 相关的问题......
编辑2:
编辑并测试了我的最后一个片段,它现在可以工作了;-)