doog1092 2018-01-09 01:03
浏览 190
已采纳

为什么php for循环停止了?

I've researched this until my brain hurts. I can't find a single explanation to why my for loop stops looping.

Basically, I have a php script that pulls images from the directory and places them onto the page for image galleries and carousels. I have it setup so that the images are randomised. And I only want a set number of images, say 2 for example.

I am using this loop:

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

While it mostly gives out a total of 2 images, occasionally it gives only 1 image and it has been known to not give an image at all.

My question is this: Why does the loop stop completely below the specified amount? And yes I've tried using 3, but that gave me 3 images which wasn't wanted.

Here is the full script:

 <?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]);                                            
        }
    }
?>  


Edit: For future use.

Thanks to Thành Chung Bùi for his answer, I have amended, changed and improved my code. Here is the full script that I use:

<?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]);
}
?>
  • 写回答

1条回答 默认 最新

  • drbae3964 2018-01-09 01:26
    关注

    The problem is you're trying to get "not loaded image" by this: $random_img = rand(1,count($images)-1);

    you may expected a new image is loaded but nothing guaranty that the new random image is truly new image so the loop skip without print anything.

    You may need to add something that check newly random image has not been loaded like this:

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

    just replace entire your if else statement inside for loop with the above code.

    Additional:

    • $random_img = rand(0,count($images)-1);
    • In the Read the directory section, i didn't see the code that set $i, also $images[$i]= $file; can be more simple: $images[]= $file;
    • You use unset function that lead unexpected result in this case (in else statement unset($images[$random_img]);). unset removes element from array but not re-index array. So your code will throw Undefined offset at some point.

    So now the code inside for loop can be

    $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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗