簡體   English   中英

PHP加權數組,用於隨機錨文本

[英]PHP- weighted array for random anchor text

嘗試設置一個簡單的嵌入框以回顯url並隨機化源錨文本。 我做到了:

<textarea class="cf" onclick="this.focus();this.select()" readonly="readonly">
<iframe src="<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>" width="550px" height="400px" frameborder="0" scrolling="auto" allowtransparency="true"><a href="http://example.com/"><?php 
$raAnchor = array(1 => 'example.com', 
           2 => 'http://example.com/', 
           3 => 'www.example.com', 
           4 => 'Click here');  
$raNumber = count($raAnchor); 
echo $raAnchor[rand(1, $raNumber)]; 
?></a></iframe>
</textarea>

問題:如何加權數組的隨機結果以支持特定回波? 例如,希望example.com在50%的時間內回顯。 我想我可以像這樣在數組中放置更多example.com:

1 => 'example.com', 
2 => 'example.com', 
3 => 'example.com', 
4 => 'example.com', 
5 => 'http://example.com/', 
6 => 'www.example.com', 
7 => 'Click here');  

似乎必須有一個更優雅的解決方案。 我是編程的新手,對php的了解最少,因此,如果您可以向正確的方向指出,我可以從那里開始。

謝謝。

你可以這樣做:

<?php
    if(rand(1,2) == 1)
    {
        //Example goes here
    }
    else
    {
        //Everything else
    }
?>

您可以間隔進行相同的操作。 例如:

<?php
    $r = rand(1,10); 
    if($r >=1 && $r < 4)
    {
        /* 30% */
    }
    else if($r >=4 && $r < 9)
    {
        /* 60% */
    }
    else
    {
        /* 10% */
    }
?>

您始終可以生成一個隨機數1-100,如果<= 40,則生成1。否則,請執行另一個隨機數以選擇2-7。

只是選擇一個較大的MAX值並以1/100為基礎進行播放(更靈活;更隨機)

if (($index = mt_rand(1,1000))<500) {
   // yes, 50%
   shuffle($arr);
   return $arr[$index];
}
else {
   // the other 50%
}

或只是隨機的:

shuffle($arr);
return $arr[ array_rand($arr) ];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM