为什么 php for 循环停止?

Why does the php for loop stop?

我一直在研究这个直到我的大脑受伤。我找不到关于为什么我的 for 循环停止循环的单一解释。

基本上,我有一个 php 脚本,可以从目录中提取图像并将它们放置到图像库和轮播页面上。我已将其设置为随机化图像。我只想要一定数量的图片,比如 2 张。

我正在使用这个循环:

$amount = 2;
for($i = 0; $i < $amount; $i++){
}

虽然它通常给出总共 2 张图像,但偶尔它只给出 1 张图像,而且众所周知,它根本不给出图像。

我的问题是:为什么循环完全停止在指定数量以下?是的,我试过使用 3,但这给了我 3 个不需要的图像。

这是完整的脚本:

 <?php
    // Set a variable for the directory
    $folderName = "Images/Gallery Images/thumbs/230x180/";
    // Open specified directory                 
    $folder = opendir($folderName);
    // Amount of images to count to
    $amount = 2;
    $loadedImages = array();

    // Read the directory
    while($file = readdir($folder)){
    // Check if file isn't a directory/sub-directory, we only want the images here...
        if(strpos($file, '.') !== 0){
            // Set image into an array
            $images[$i]= $file;
            // Move on to next image.
            $i++;
        }
    }
    // Count images upto predefined amount
    for($i = 0; $i < $amount; $i++){ 
    // Randomise the images, so we get completely random images each page load
        $random_img = rand(1,count($images)-1);

        // Check if array isn't empty
        // Otherwise it was sometimes getting empty values as an image
        if(empty($images[$random_img]) || !isset($images[$random_img])) {
            // If so, try another one
            $random_img = rand(1,count($images)-1);
        }
        // Check if image is already loaded
        if(in_array($images[$random_img], $loadedImages)){
            // If so, try another one
            $random_img = rand(1,count($images)-1);
        }
        // If all images passes the conditions write them into the page
        else {              
            // Echo out the image tag with the size attribute and src
            echo '<img src="'.$folderName.$images[$random_img].'" alt="Photo '.pathinfo($images[$random_img], PATHINFO_FILENAME).'">';
            // Add the image to the loadedImages array
            array_push($loadedImages,$images[$random_img]);
            // Unset each image in original array so we don't have double images
            unset($images[$random_img]);                                            
        }
    }
?>  


编辑:供将来使用。

感谢 Thành Chung Bùi 的 ,我修改、更改和改进了我的代码。这是我使用的完整脚本:

<?php
// Set a variable for the directory
$folderName = "Images/Gallery Images/";
// Open specified directory                 
$folder = opendir($folderName);
// Amount of images to count to
$amount = 2;
// Set an empty array for the images
$images = array();
// Set an empty array for the loaded images
$loadedImages = array();

// Read the directory and set all images into the image array
while (false !== ($file = readdir($folder))) {
    // Check if file is a regular file, we don't want directories or sub-directories, only images...
    if (is_file($folderName . $file) == true) {
        // Set image into the image array
        array_push($images, $file);
        // Move on to next image.
        $file++;
    }
}
closedir($folder);

// Count images upto predefined amount
for ($i = 0; $i < $amount; $i++) {
    // Randomise the images
    $random_img = array_rand($images);

    // If a random image has already been loaded using the loadedImages array or is empty...
    while (in_array($images[$random_img], $loadedImages) || empty($images[$random_img])) {
        // Pick another random image
        $random_img = array_rand($images);
    }
    // Get image width/height
    list($width, $height, $type, $attr) = getimagesize($folderName . $images[$random_img]);
    // Echo out the random image and set the width and data-width to be used later in JavaScript
    echo '<img src="' . $folderName . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" style="width:' . $width . 'px;" data-width="' . $width . 'px;">';

    // Add the random image into the loadedImages array, so we can check against it
    array_push($loadedImages, $images[$random_img]);
}
?>

问题是您正试图通过以下方式获得 "not loaded image": $random_img = rand(1,count($images)-1);

您可能希望加载新图像,但无法保证新随机图像是真正的新图像,因此循环跳过而不打印任何内容。

您可能需要添加一些东西来检查新的随机图像是否没有像这样加载:

while(in_array($images[$random_img], $loadedImages)){
    $random_img = rand(1,count($images)-1);
}

只需用上面的代码替换 for 循环中的整个 if else 语句。

补充:

  • $random_img = rand(0,count($images)-1);
  • Read the directory部分,我没有看到设置$i的代码,另外$images[$i]= $file;可以更简单:$images[]= $file;
  • 在这种情况下(在 else 语句 unset($images[$random_img]); 中),您使用 unset 函数导致意外结果。 unsetarray 中删除元素,但不从 re-index 数组中删除元素。所以你的代码会在某个时候抛出 Undefined offset

所以现在for循环里面的代码可以是

$random_img = rand(0,count($images)-1);
while(in_array($images[$random_img], $loadedImages)){
    $random_img = rand(0,count($images)-1);
}
echo '...';
array_push($loadedImages,$images[$random_img]);