Image Shuffle and Randomising - only randomising the first 4 images

5 posts by 2 authors in: Forums > CMS Builder
Last Post: August 7, 2013   (RSS)

Hi,

You can randomise the order of the galleries as well as its images by shuffling the gallery array as well:

<?php
    
  // load records from 'galleries'
  list($gallery, $galleriesMetaData) = getRecords(array(
    'tableName' => 'galleries',
    'orderBy' => 'RAND()',
    'loadUploads' => true,
    'allowSearch' => false
  ));

  //shuffle all of the images for each record
  foreach($gallery as $images){
    shuffle($images['images']);
  }
  shuffle($gallery);

  //counter
  $n = 0;
  //max number of images you want to pull from each section;
  $max = 7;
  while($n <= $max):

?>

This will shuffle the the items in the gallery array after all of the images in each gallery record has been shuffled.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

By benedict - August 6, 2013

I still get the same result as before - it switches the galleries around, but is not randomising the images at all. It keeps showing the first image in each gallery.

Hi benedict, 

The problem is that when you use a foreach loop, you can't edit the compontents inside of it unless you makes changes to the array directly, I think you need to change your foreach loop for the galleries to this:

<?php
    
  // load records from 'galleries'
  list($gallery, $galleriesMetaData) = getRecords(array(
    'tableName' => 'galleries',
    'orderBy' => 'RAND()',
    'loadUploads' => true,
    'allowSearch' => false
  ));

  //shuffle all of the images for each record
  foreach($gallery as $key=> $images){
    shuffle($gallery[$key]['images']);
  }
  shuffle($gallery);

  //counter
  $n = 0;
  //max number of images you want to pull from each section;
  $max = 7;
  while($n <= $max):

?>

So now the foreach loop cycles through each element and uses its key to make changes to the item directly on the array.

Let me know if you have any questions.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

By benedict - August 7, 2013

Boom. Works. You beauty! Thanks, mate.