简体   繁体   中英

PHP- weighted array for random anchor text

trying to set up a simple embed box to echo url and randomize source anchor text. I achieved both with this:

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

The problem: how do I weight random results from the array to favor a particular echo? For example, would like example.com to echo out 50% of the time. I guess I could just put more example.com in the array like this:

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

Seems there has to be a more elegant solution. I'm new to programming, and php I understand the least so if you could point me in the right direction I can take it from there.

Thanks.

You can do this:

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

You can do the same with intervals. For example:

<?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。

just pick a big MAX value and play it in 1/100 basis (more flexible;more random)

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

or just random:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM