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

报告相同问题?

悬赏问题

  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM
  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程