|
Posted by Curt Zirzow on 12/16/05 09:47
On Thu, Dec 15, 2005 at 08:45:33PM -0800, Mike Rondeau wrote:
> Hi,
>
> I'm still very green with PHP, but am working to fix that.
>
> I've searched high and low for an answer to this question and so far
> no solution has presented itself. I have a script to populate my web page
> with random images:
>
> <?php
> #random images example
> #this is your file
> $file = "images.txt";
> #open the file
> $openFile = file($file);
> #generate a random number
> srand((double)microtime()*1000000);
> #get one of the entries in the file
> $random_image = $openFile[array_rand($openFile)];
> #display the entry
> echo "<img src='$random_image' height='170' width='100'></img>";
> ?>
>
>
> This works beautifully, but my problem is that sometimes, the same image
> displays twice or more on the same page-load. My page requires 10 different
> places where my images need to load, but I can't have any duplicate images
> show up.
Depending on the complexity of the logic you want in selecting
random images you can do something like:
$files = file($file);
$want = 10; // how many I want
$max = count($files); // the range, we might need -1
// a simple range check, to avoid an infinate loop
$can_have = $want > $max? $max: $want;
// start off the loop with these values
$have = 0; // aka have none
$images = array(); // aka no random images
do {
// generate a random number
$random = mt_rand(0, $max);
// if we dont have it..
if(! isset($images[$random]) ) {
$have++;
$images[$random] = $files[$random];
}
// have we made it there yet?
} while($have < $can_have)
var_dump($images);
foreach($images as $random_image) {
echo "<img src='$random_image' height='170' width='100'></img>";
}
Now, keep in mind that if you have 15 images and you want 10, this
could potentially be very intensive on the cpu.
On the other hand if you have 10,000 images and are looking for 10
it wont be as intensive on the cpu, but will use a lot of memory
that really shouldn't be used by loading the file into an array. At
this point an index file should be used or a DB solution should be
considered.
Curt.
--
cat .signature: No such file or directory
[Back to original message]
|