Skip to content

Instantly share code, notes, and snippets.

@andreconghau
Created June 27, 2017 12:20
Show Gist options
  • Save andreconghau/a8780ecce7642e9c0ffcb941179c551a to your computer and use it in GitHub Desktop.
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.
<?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