我有以下代码:
for($i=0; $i<count($gallery);$i++)
{
$temp = array();
$temp = $gallery[$i];
echo "<img src='". $temp->path . "' />";
}
现在,此代码将内容打印在一行中。我希望每一行只打印3行,然后创建新行,然后再打印3行等等。这是如何做到的呢?
(感谢支持:)
编辑:错误
遇到PHP错误 严重程度:通知 消息:未定义偏移量:5 文件名:view/profile.php 线路号码: 105 遇到PHP错误 严重程度:通知 消息:尝试获取非对象的属性。 文件名:view/profile.php 线路号码: 106
发布于 2013-04-17 20:32:06
你能做到的
$n = 3;
echo "<table><tr>";
for($i=0; $i<count($gallery);$i++){
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
if($i % $n ==0 && $i!=0 ){
echo "</tr><tr>";
}
}
echo '</tr></table>';
编辑:
如果您想要以“正确”的方式进行--通过构建语法正确的HTML,您需要这样做:
$n = 3;
echo "<table><tr>";
$gallery_count = count($gallery);
for($i=0; $i<$gallery_count; $i++){
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
if($i != 0){
if($i % $n == 0 && $i != $gallery_count-1){
echo "</tr><tr>";
}
else{
echo ""; //if it is the last in the loop - do not echo
}
}
}
//example - if the last 2 `td`s are missing:
$padding_tds = $gallery_count % $n;
if($padding_tds != 0 ){
$k = 0;
while($k < $padding_tds){
echo "<td> </td>";
}
}
echo '</tr></table>';
发布于 2013-04-17 20:33:42
您只需要一个modulus
来检查已经打印了多少-任何3的倍数都会增加一个中断。
$x=0;
for($i=0; $i<count($gallery);$i++)
{
$x++;
$temp = array();
$temp = $gallery[$i];
echo "<img src='". $temp->path . "' />";
if (($x%3)==0) { echo "<br />"; }
}
发布于 2013-04-17 20:47:29
我只是用表格重做了一遍,它更整洁了,因为每件事都会被格式化,以正确地看上去。这有点混乱,因为我只是添加了一些if语句来发布表。
<table>
<?php
$number_per_row = 3;
for($i=0; $i<count($gallery);$i++)
{
$temp = array();
$temp = $gallery[$i];
if(($i % $number_per_row) == 0) {
echo "<tr>";
}
?>
<td><?php echo "<img src='". $temp->path . "' />"; ?></td>
<?php
if(($i % $number_per_row) == $number_per_row - 1) {
echo "</tr>";
}
}
?>
</table>
https://stackoverflow.com/questions/16069692
复制相似问题