這裏是我的執行速度快:
<?php
$urls = array(
array('url' => 'http://google.com', 'weight' => 50),
array('url' => 'http://microsoft.com', 'weight' => 13),
array('url' => 'http://apple.com', 'weight' => 42),
);
$total_weight = 0;
foreach ($urls as $url) {
$total_weight += $url['weight'];
}
$rand = mt_rand(1, $total_weight);
var_dump($rand);
$selected_url = '';
foreach ($urls as $url) {
$rand -= $url['weight'];
if ($rand <= 0) {
$selected_url = $url['url'];
break;
}
}
var_dump($selected_url);
另外一個,多了幾分ellegant:
<?php
$urls = array(
array('url' => 'http://google.com', 'weight' => 50),
array('url' => 'http://microsoft.com', 'weight' => 13),
array('url' => 'http://apple.com', 'weight' => 42),
);
$probs = array();
foreach ($urls as $i => $url) {
$probs = array_merge($probs, array_fill(1, $url['weight'], $i));
}
$rand = array_rand($probs);
var_dump($rand);
var_dump($urls[$probs[$rand]]['url']);