如何优先进行随机? [英] How to do random with priority?

查看:38
本文介绍了如何优先进行随机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,例如:

<?php
     $arr = array(
          array("url" => "http://google.com", "priority" => 2),
          array("url" => "http://facebook.com", "priority" => 2),
          array("url" => "http://youtube.com", "priority" => 2),
          array("url" => "http://stackoverflow.com", "priority" => 1),
          array("url" => "http://kickass.to", "priority" => 1),
          array("url" => "http://twitter.com", "priority" => 1),
          array("url" => "http://example.com", "priority" => 1),
     );
?>

我希望系统在每次刷新时随机显示一个 url.我希望它比低优先级显示更多次.我需要它用于横幅系统,优先级高的支付更多,所以他们应该被更多人看到.

I want the system to randomly display one of the url's on each refresh. I want it to display the higher priority more times than the lower. I need it for banner system, and the ones with higher priority paying more, so they should be seen more.

怎么做?

推荐答案

迭代所有横幅,并为每个横幅分配一个键(数字 id).对于那些具有更高优先级的人,分配 2 个键(如果您希望更高的优先级,则分配更多).然后只需找到 0(假设它是从零开始的)和键总数之间的随机数:

Iterate over all the banners, and assign a key (numeral id) for each. To those with a higher priority, assign 2 keys (or more if you wish an even higher priority). Then just find the random number between 0 (assuming it's zero-based) and the total number of keys:

rand(0, count($keys) - 1);

<小时>

更新

这是一些代码:

// $arr = Your original array

$keys = array();
for ($i = 0; $i < count($arr); $i++) { // you can also use foreach here
     for ($u = 0; $u < $arr[$i]['priority']; $u++) {
         $keys[] = $i;      
     }
}

然后,要获取一个随机 url,但有优先级,请执行以下操作:

Then, to fetch a random url, but with priorities, do this:

$arr[ $keys[ rand(0, count($keys) - 1) ] ];

这篇关于如何优先进行随机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆