问题
I rotate a banner on my site by selecting it randomly from an array of banners.
Sample code as demonstration:
<?php
$banners = array(
'<iframe>...</iframe>',
'<a href="#"><img src="#.jpg" alt="" /></a>',
//and so on
);
echo $banners(rand(0, count($banners)));
?>
The array of banners has become quite big. I am concerned with the amount of memory that this array adds to the execution of my page. But I can't figure out a better way of showing a random banner without loading all the banners into memory...
回答1:
Move the banners to html files and change the array to contain only filenames.
Then you can include that file by the name, only loading the banner required.
回答2:
Create a database to store the banners in. Then when you do your page load, you could use a SQL query to select a random row.
SELECT * FROM banners ORDER BY RAND() LIMIT 1
回答3:
A way to do this without requiring array memory or a database, is to follow an incremental image naming convention, for example naming your images "banner1.jpg", "banner2.jpg", etc. Then you can just do this:
$int_banners = 10; // the number of banner images you have
$i = rand(1, $int_banners);
echo "<a href='#'><img src='banner$i.jpg' alt=''></a>"; // add an iframe too if you want
If you cannot use such a convention, then you can create an array with just the file names (or use a SQL database to store the banners, as suggested in other answers).
$lst_banners = array("img1.jpg", "/home/img2.jpg", "/about/img3.jpg");
$int_banners = count($lst_banners);
$i = rand(0, ($int_banners - 1));
echo "<a href='#'><img src='" . $lst_banners[$i] . "' alt=''></a>";
Or better, you can use array_rand() to find the filename, as suggested by Zlatan:
$lst_banners = array("img1.jpg", "/home/img2.jpg", "/about/img3.jpg");
$name = array_rand($lst_banners, 1);
echo "<a href='#'><img src='$name' alt=''></a>";
来源:https://stackoverflow.com/questions/13108097/efficient-banner-rotation-with-php