将每个X结果加载到不同的div中

时间:2015-04-21 13:04:45

标签: php html mysql css

我有这个html结构:

<div id="content" class="container">

  <div class="item">
     <img src="image" alt="" />
  </div>  
</div>

我将图片加载到这个div中 - item就像这样:

$stmt = $pdo->prepare("SELECT * FROM images WHERE album = ? ORDER BY image_id DESC");
$stmt->execute(array($album_id));
$data = $stmt->fetchAll();
foreach ($data as $row)
{                                                    
    echo '
          <div class="item">
              <img src="'.$row['image_path'].'" alt="" />
          </div>';        
}   

我的问题是可以在foreach循环中添加第二个div并将每个第3个图像放入其中。像这样:

<div id="content" class="container">

  <div class="item">
     <img src="image" alt="" />
  </div>  
 <div class="third-item">
     <img src="image" alt="" />
  </div> 
</div>

希望你理解我的意思。

3 个答案:

答案 0 :(得分:1)

添加循环增量变量并使用模数运算符,如下所示:

my $i = 0;
foreach ($data as $row)
{                                                    
    echo '
      <div class="item">
          <img src="'.$row['image_path'].'" alt="" />
      </div>';        
    if ($i % 3 == 0)
    {
     echo '<div class="third-item">
          <img src="'.$row['image_path'].'" alt="" />
      </div>'; 
    }
    $i++;
}  

答案 1 :(得分:1)

尝试使用这样:

$stmt = $pdo->prepare("SELECT * FROM images WHERE album = ? ORDER BY image_id DESC");
$stmt->execute(array($album_id));
$data = $stmt->fetchAll();
$i = 0;
$res="";
foreach ($data as $row)
{                                                    
    $res.='
      <div class="item">
          <img src="'.$row['image_path'].'" alt="" />
      </div>';        
    if ($i % 3 == 0)
    {
       $res.='<div class="third-item">
          <img src="'.$row['image_path'].'" alt="" />
      </div>'; 
    }
    $i++;
}  

echo $res;

答案 2 :(得分:1)

你好我的朋友你可以使用两个内部循环:

    <?PHP
echo '<div id="content" class="container">';

for($i = 0; $i < count($data); $i++) {
echo '<div id="content" class="container">';
    for ($j=0; $j < 3 ; $j++) {
        if($j == 2){
            echo ' <div class="third-item">';
            echo '<img src="image" alt="" />';
            echo '</div>';
        }else {
            echo '  <div class="item">';

            echo '<img src="image" alt="" />';
            echo "</div>";
        }
    }
}
echo "</div>";