PHP返回一个数组中的前三个元素然后另外三个[关闭]

PHP返回一个数组中的前三个元素然后另外三个[关闭]

问题描述:

I have an array of 20 elements and each element in the array holds an image. I'm making it so the image sizes alternate. Three images should be medium size, then next four are small, and 7th is large. Pattern should continue till end of the array. Right now I have it working so that every 7th image is large, and the rest are small. I'm not sure what the best way would be to set up the medium images. So: Array[]

[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
[12]
[13]
[14]
[15]
[16]
[17]
[18]
[19]
[20]

I would want [0], [1], [2], [8],[9],[10],[15],[16],[17] to all be medium sized.

Here's my code below.

        foreach ($images as $image ) {
                $img_size = "small";
                if($i !==0 && $i % 7 == 0) {
                    $img_size = "large";
                }else{
                    $img_size = $img_size;
                }
        }

Some if/else logic:

<?php

$m = 3;
$s = 7;
$l = 8;

$counter = 1;
for($i=0;$i<=20;$i++){
    if($counter <= $m){
        $img_size = "medium";
    }elseif($counter <= $s){
        $img_size = "small";
    }else{
        $img_size = "large";
    }
    if($counter == $l) $counter = 0;

    $counter++;
    echo "i = $i and img_size = $img_size <br>";
}

?>

Try this:

$i = 0;
$count = count($a)-1; // get the maximum index of array $a

while ($i <= $count) {

    echo $a[i];
    if ($i+1 <= $count) echo $a[$i+1];
    if ($i+2 <= $count) echo $a[$i+2];

    $i+=8;
} // while