2013-09-23 38 views
-2

裝,我有以下代碼:插入圖像之間的隨機碼從MySQL表

<?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代碼,任何人都可以幫助,我呢?

+1

你是什麼意思「在隨機位置」?你甚至想要做什麼? – jedwards

+1

只需在回聲後添加adsense代碼? – Martijn

+0

您只希望廣告出現一次嗎?或者你想讓它有機會出現在每張圖片之間? – KHMKShore

回答

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> 
2

添加的,而一些代碼:

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---"; 
    } 
} 
+0

並在每4張圖片後加載AdSense代碼? –

+0

@CaioKawasaki如果你想這樣做,只需要在你的數組中有一個計數器。你會做類似'if($ counter%4 == 0){echo「adsense code」; }而不是'mt_rand()'函數的if語句。 – SamT