Created
June 27, 2017 12:20
-
-
Save andreconghau/a8780ecce7642e9c0ffcb941179c551a to your computer and use it in GitHub Desktop.
Random một array và lấy ra item với xác xuất cố định.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function weightedRand($stream) { | |
$pos = mt_rand(1,array_sum(array_keys($stream))); | |
$em = 0; | |
foreach ($stream as $k => $v) { | |
$em += $k; | |
if ($em >= $pos) | |
return $v; | |
} | |
} | |
$item['5'] = 'I have more chances than everybody :]'; | |
$item['10'] = 'I have good chances'; | |
$item['10'] = 'I\'m difficult to appear...'; | |
for ($i = 1; $i <= 100; $i++) { | |
echo weightedRand($item).'<br />'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment