Can I create a random order in a foreach loop

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Guest
Hi,
I have a gallery website with the following code to display images:
Code:
<?php
$json = file_get_contents('js/rivka-img.json');
$data = json_decode($json, true);
$galleryRivka = $data['galleryRivka'];
foreach ($galleryRivka as $entry) {
  echo '<div class="main">  <div class="numbertext">'.$entry['medium']
       ."<hr>".$entry['titleEng'].'<hr> '.$entry['width']."cm x ".$entry['height']
       .'cm</div>  <img class="example" src="images/recent/'. $entry['imgMain']
       .'" data-magnify-src="images/recent/'. $entry['imgMain']
       .'">  </div>';
}
?>
I would like to change the order the images appear - say once a day, so my question is , is there any way to randomize the order the images are shown. The information displayed is in json format.
Thanks for any help.
 
There is a function to sort the array in random order: shuffle()
The function modify the variable passed as a parameter
php doc: https://www.php.net/manual/en/function.shuffle.php
Code:
<?php

$json = file_get_contents('js/rivka-img.json');
$data = json_decode($json, true);
$galleryRivka = $data['galleryRivka'];

// randomize order
shuffle($galleryRivka);

foreach ($galleryRivka as $entry) {
    ?>
    <div class="main">
        <div class="numbertext">
            <?php echo $entry['medium']; ?>
            <hr>
            <?php echo $entry['titleEng']; ?>
            <hr>
            <?php echo $entry['width'] . 'cm x ' . $entry['height'] . 'cm'; ?>
       </div>
       <img class="example" src="images/recent/<?php echo $entry['imgMain']; ?>" data-magnify-src="images/recent/<?php echo $entry['imgMain']; ?>">
    </div>
    <?php
}
 
Back
Top