Request Brochure

Blog & News

Randomizing your Flickr to vBulletin Feed

instructor helping student at computer tech camp

Last time I discussed pulling your Flickr feed into a vBulletin installation (or really, any php-based CMS/website). That solution pulled the lastest photos up to some amount and displayed them. But what if you want to randomize them and not always display the pictures in the same order? We’ll be pulling a large amount of photos from Flickr and I don’t always want only the last ones to show up in the same order. Instead, I’d like to pull the last, say, 200 photos and randomly display 10 of them. Here’s the code modification from last week’s post:

require_once("includes/phpFlickr.php");

// Create new phpFlickr object
$f = new phpFlickr("yourapikey");

$f->enableCache("db","mysql://user:password@server/database");

$limit = 200;
$count = 10;

// Find the NSID of the username inputted via the form
$person = $f->people_findByUsername('iDTechCamp');

// Get the friendly URL of the user's photos
$photos_url = $f->urls_getUserPhotos($person['id']);

// Get the user's first X($limit) public photos
$photos = $f->people_getPublicPhotos($person['id'], NULL, NULL, $limit);

$flickrbox = "<table class='flickrbox'><tr>";
$nonrepeatarray = array();

for ($i = 0; $i < $count; $i++) {
    $rand = rand(0,199);
    while(in_array($rand,$nonrepeatarray)) $rand = rand(0,199);
    array_push($nonrepeatarray, $rand);

    $photo = (array)$photos['photos']['photo'][$rand];
    $flickrbox .= "<td><a class='flickrimg' href=$photos_url$photo[id]>";
    $flickrbox .= "<img border='0' alt='$photo[title]' "
               ."src=" . $f->buildPhotoURL($photo, "Square") . ">";
    $flickrbox .= "</a></td>";
}

$flickrbox .= "</tr></table>";

You can see I’ve highlighted the altered sections in red. First, we up the $limit to 200. Then we introduce a new variable, $count. This variable will contain the number of photos we’d like displayed of the 200 we’re pulling. Next we change our foreach loop into a regular for loop. We will then randomly generate a number between 0 and 199 (remembering that arrays begin at 0, not 1). We run a while loop to check if that number is already in an array we’ve been keeping called $nonrepeatarray. If it is there, we draw another number. If it isn’t, we exit that loop, add it to the array, and keep moving with the portion of the loop dedicated to building the image display.

Although this may not be the most efficient method, it is simple. Plus, we have caching enabled through the phpFlickr API, so that will help. Other ways of doing the exact same thing include generating an array containing the values 0-199, shuffling the array, and then popping off one element each time. You are guaranteed not to have repeats.

For other methods of generating random, non-repeating numbers, with sample code, see here: http://www.phpbuilder.com/board/showthread.php?t=10329337.