dongxiqian2787 2010-06-05 02:25
浏览 23
已采纳

与PHP随机广告配对链接

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>
  • 写回答

2条回答 默认 最新

  • dongzhangnong2063 2010-06-05 03:09
    关注

    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;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改