-3

我有以下代码:

<?php

    mysql_connect("localhost","root","");
    mysql_select_db("bravo");
    $res=mysql_query("select * from coisas");

?>
<div>
<?php
    while ($row=mysql_fetch_array($res)) {

    echo "<img src=\"{$row['imagem']}\">";

    }
?>
</div>

我需要在图像之间的随机位置显示一个 AdSense 代码,有人可以帮我吗?

4

2 回答 2

2

在while中添加一些代码:

while ($row=mysql_fetch_array($res)) {
   echo "<img src=\"{$row['imagem']}\">";
   echo "--- adsense code here---";
}

它将在每张图像之后注入它。

或者,如果您真的想将其放置在完全随机的位置:

$chanceOfAdsense = 35; // 35% chance of adsense appearing between any given images

while ($row=mysql_fetch_array($res)) {
   echo "<img src=\"{$row['imagem']}\">";

   if (mt_rand(0,99) < $chanceOfAdsense) {
      echo "--- adsense code here---";
   }
}
于 2013-09-23T18:34:52.480 回答
0

从 while 循环构建一个输出数组,然后计算其中的值的数量。使用 count(array) 使用 rand() 计算随机数,然后迭代输出数组,并使用 if 语句判断索引何时与随机数匹配。

<?php

    mysql_connect("localhost","root","");
    mysql_select_db("bravo");
    $res=mysql_query("select * from coisas");

?>
<div>
<?php
    $output_array = array();
    while ($row=mysql_fetch_array($res)) {

      $output_array[] = "<img src=\"{$row['imagem']}\">";

    }

    //If you want the image to appear closer to middle, use fractions of $output_array
    //EG: rand(count($output_array)/3, count($output_array)*2/3));
    $rand_key = rand(0, count($output_array)-1);

    foreach ($output_array as $key => $img) {
       if ($key == $rand_key) {
           //echo your adsense code
       }
       echo $img;
    }
?>
</div>
于 2013-09-23T18:34:08.370 回答