nfq
nfq

Reputation: 113

PHP shuffle, multiple loop

I want to shuffle 2 loops (or function) in the same correct order, in PHP.

The code currently looks like:

<div class="overlay">

<?php

    // Get the list of all files with .jpg extension in the directory and save it in an array named $images
    $directory = "uploads/_gallery/*.jpg";

    // Create an array of images found in the uploads directory
    $images = glob($directory);

    // Randomise/shuffle the images
    shuffle($images);

    foreach( $images as $image ):
        if ($image) { ?>
            <div class="slide">
                <?php echo "<img src='" . $image . "'>"; ?>
            </div>
        <? }
    endforeach;

?>

</div>

<div class="grid">

<?php

    // Get the list of all files with .jpg extension in the directory and save it in an array named $images
    $directory = "uploads/_gallery/thumbs/*.jpg";

    // Create an array of images found in the uploads directory
    $images = glob($directory);

    // Randomise/shuffle the images
    shuffle($images);

    foreach( $images as $image ):

        if ($image) { ?>
            <figure class="unit_25">
                <?php echo "<img src='" . $image . "'>"; ?>
            </figure>
        <? }

    endforeach;

?>

</div>

I've tried creating two separate image arrays and merging those with Shuffle, but no luck.

Upvotes: 0

Views: 98

Answers (1)

JesusTheHun
JesusTheHun

Reputation: 1237

I assume the file has the same name in both directory. So shuffle $images and then use basename($images) to get the filename :

$directory = "uploads/_gallery/*.jpg";
$images = glob($directory);
shuffle($images);


// For full sized images
foreach ($images as $image) {
    // Your stuff
}

// For thumbnails
foreach ($images as $image) {
    $basename = basename($image);
    $thumbnailPath = "uploads/_gallery/thumbs/". $basename;
    // Your stuff
}

Upvotes: 1

Related Questions