遍历图像文件夹,每次返回接下来的 3 张图像


loop through image folder and return the next 3 images each time

我目前有一个图像文件夹,我正在尝试使用 AJAX 调用进行循环访问,我想一次只返回 3 个直到结束,然后从头开始。

如果达到终点,我无法提出从头开始部分的逻辑。

这是我目前所拥有的。

$images = glob("images/*.jpg");
// sort images by file time
usort($images, function($a, $b) {
     return filemtime($a) < filemtime($b);
});
$images = array_slice($images, $start_pos, 3);

要将图像切成 3 组,$start_pos为 0,然后在第一次调用后,最多 3 返回图像 4,5,6。但是目前,如果我的图像不超过 3 张,则设置 3 张图像$start_pos不会返回任何内容,而不是重新开始。

if (count($images) > 3) {
    $start_pos += 3;
}
$images = array_slice($images, $start_pos, 3);

使用模数循环

$selectedImages=array();
$imageNum=0;
for($i=$start_pos%count($images);$imageNum<3;i=(i+1)%count($images),$imageNum++)
{
    $selectedImages[$imageNum]=$images[$i]
}