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

I have an array in PHP with 24 items and I want to make a loop and after each 8 items I want to display an image. The problem is that there are 3 distinct images that have to be displayed in order after each 8 items.

How can I accomplish this?

Just do it, array_chunk is often helpful for such:

$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
}
$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


Update

If your array is not numerically indexed, use @hakre's solution, because that one doesn't take into account the numerical ids of the array.

Try something like this:

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

NOTE: The images are numbered: 0, 1 and 2

The Modulo-Operator is what you're looking for:

<?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.']'."
";
  if($i && $i%8==0) {
    echo '<img src="'.$images[$i/8].'" alt="">';
  }
}

This will produce the following output:

$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="">