循环遍历数组并在每8个项目后显示图像

时间:2011-10-26 11:50:43

标签: php arrays

我在PHP中有一个包含24个项目的数组,我想创建一个循环,在每个8项后我想显示一个图像。问题是每8个项目后必须按顺序显示3个不同的图像。

我该如何做到这一点?

4 个答案:

答案 0 :(得分:3)

只要这样做,array_chunk通常对此有用:

$items = array(...);
$imgs = array('img1', 'img2', 'img3');

$groups = array_chunk($items, 8);    
foreach($groups as $group)
{
    foreach($group as $item)
    {
        # 8 items
    }
    $image = array_shift($imgs); # your image
}

答案 1 :(得分:2)

尝试这样的事情:

$i=0;
$j=0;
foreach($array as $item)
{
    if(($i > 0) && ($i%8 == 0))
    {
        // Show the image ($j%3)
        $j++;
    }
    $i++;
}

注意:图像编号为:0,1和2

答案 2 :(得分:1)

$array = array();
$imgs = array('img1', 'img2', 'img3');

// fill the array (you don't need this, since you already have the array)
for($i = 0; $i < 24; $i++){
    $array[$i] = $i+1;
}

// show the items
foreach($array as $id => $arr){
    echo $arr;
    if( (($id+1)%8) == 0) echo $imgs[(($id+1)/8)-1];
}

Demo


更新

如果你的数组没有数字索引,请使用@hakre的解决方案,因为那个没有考虑数组的数字id。

答案 3 :(得分:0)

Modulo-Operator正是您所寻找的:

<?php

$items = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);
$images = array(
  1 => 'http://placekitten.com/100/100?image=1',
  2 => 'http://placekitten.com/100/100?image=2',
  3 => 'http://placekitten.com/100/100?image=3'
);

for($i = 0; $i < count($items); $i++) {
  echo '$items['.$i.']'."\n";
  if($i && $i%8==0) {
    echo '<img src="'.$images[$i/8].'" alt="">';
  }
}

这将产生以下输出:

$items[0]
$items[1]
$items[2]
$items[3]
$items[4]
$items[5]
$items[6]
$items[7]
$items[8]
<img src="http://placekitten.com/100/100?image=1" alt="">$items[9]
$items[10]
$items[11]
$items[12]
$items[13]
$items[14]
$items[15]
$items[16]
<img src="http://placekitten.com/100/100?image=2" alt="">$items[17]
$items[18]
$items[19]
$items[20]
$items[21]
$items[22]
$items[23]
$items[24]
<img src="http://placekitten.com/100/100?image=3" alt="">
相关问题