So I have the following code with works great for randomly generating position for 5 different sidebar ads, my problem is how to give the ads a link that will always be paired with them.
I'm looking for suggestions from some PHP gurus as to best practices for doing this...
<ul class="top_ads">
<?php
$totalImages = 5;
$all = range(1,$totalImages);
shuffle($all);
foreach ($all as $single) {
echo "<li><a href='' /><img src='"; echo bloginfo('template_url') . "/images/ads/ad_0$single.png' alt='ad' /></li>";
}
?>
</ul>
The simplest way is to have an array of images with links and then have $single be the array index. There are two ways to accomplish this. One is to have a two dimensionsal array that contains both links and images, the other is to have two parallel arrays. Here are both options illustrated:
<?php
// one two dimensional array
$ads = array( array("1.png", "/page1"), array("2.png", "/page2"), array("3.png", "/page3"), array("4.png", "/page4"), array("super-special-buy-now.png", "/billy-mays-lives") );
// or two one dimensions arrays
$ads_images = array("1.png", "2.png", "3.png", "4.png", "super-special-buy-now.png");
$ads_links = array("/page1", "/page2", "/page3", "/page4", "/billy-mays-lives");
// now your code
$totalImages = 5;
$all = range(1,$totalImages);
shuffle($all);
$html = "";
foreach ($all as $single) {
// option 1, two dimensional array
$html += sprintf('<li><a href="%s"><img src="%s/images/ads/ad_0%s" alt="ad" /></li>',
$ads[$single][1], bloginfo('template_url'), $ads[$single][0]);
// option 2, two parallel arrays
$html += sprintf('<li><a href="%s"><img src="%s/images/ads/ad_0%s" alt="ad" /></li>',
$ads_links[$single], bloginfo('template_url'), $ads_images[$single]);
}
echo $html;
?>
Normally you would either:
- Shuffle them already in query which retrieves them from a database, or
- Shuffle an array of id/url pairs:
$d => array (
array('id'=>1,'url'=>'...'),
array('id'=>2,'url'=>'...')
array('id'=>3,'url'=>'...'));
array_shuffle($d);
Which would also make it easier to drop add 1 instead over overwriting it (with all server / browsercaching problems that could come from it).