我有以下代码:
for($i=0; $i<count($gallery);$i++)
{
$temp = array();
$temp = $gallery[$i];
echo "<img src='". $temp->path . "' />";
}
现在,此代码将内容打印在一行中。我想每行只打印3行,然后创建新行并打印另外3行,依此类推。怎么办呢?
感谢支持:)
编辑:错误
遇到PHP错误
严重性:注意
消息:未定义的偏移量:5
文件名:views / profile.php
行号:105
遇到PHP错误
严重性:注意
消息:尝试获取非对象的属性
文件名:views / profile.php
行号:106
答案 0 :(得分:5)
你可以做到
$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>';
答案 1 :(得分:0)
您只需要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 />"; }
}
答案 2 :(得分:0)
我只是用表格重新编写它,它更整洁,因为每个东西都会被格式化为正确的。 这有点乱,因为我刚添加了一个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>
答案 3 :(得分:-1)
$n = 3;
echo "<table>";
echo "<tr>";
for($i=0; $i<count($gallery);$i++){
if(($i % n ==0) && ($i != 0)){
echo "</tr><tr>";
}
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
}
echo "</tr>";
echo '</table>';``