2

I use this query to parse a JSON feed from a flickr account and inject the code of the latest 12 photos from that feed in a div named #photos

<script type="text/javascript">
                // Set variables needed for query
                var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
                var ID = "<?php echo get_option('of_flickrid') ?>";
                var jsonFormat = "&lang=en-us&format=json&jsoncallback=?";

                var ajaxURL = URL + "?id=" + ID + jsonFormat;
                // Get the last photos of the flickr account, parse it into HTML code
                $.getJSON(ajaxURL, function(data){
                     var htmlString = '<a href="<?php echo get_option('of_flickr') ?>" target="_blank"><h1><?php echo get_option('of_photostext') ?></h1></a><br class="clear"/>';

                    // Now start cycling through our array of Flickr photo details
                    $.each(data.items, function(i,item){

                        // I only want the ickle square thumbnails
                     var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");

                        // Here's where we piece together the HTML
                        htmlString += '<a href="' + item.link + '" target="_blank">';
                        htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
                        htmlString += '" alt="'; htmlString += item.title + '" class="rounded"/>';
                        htmlString += '</a>';
                        if(i === 11){
                            return false;
                        }
                    });             

                    // Pop our HTML in the #images DIV
                    $('#photos').html(htmlString);

                }); // End getJSOON
</script>

but I need to load 12 random photos rather than the latest 12, how can I do this?

hamama
  • 121
  • 2
  • 11

1 Answers1

1

Dump them all into an array, then splice out elements at random. Since .splice() actually removes elements from the original array, you won't have to worry about extracting the same item twice.

$.getJSON(ajaxURL, function(data){
   var items = data.items, // array
       extract = [], // array
       max = 12; // number of items to remove
   for (var i=0; i<max; i++) {
     var rand = Math.floor(Math.random()*items.length); // a random index
     extract.push(items.splice(rand,1)[0]); // splice() returns an array
   };
   // do something with 'extract'
});
Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180