我想要一种方法从数组中选择一个随机元素,其中元素被挑选的概率表示为每个元素的百分比。
数组可能是JSON格式或PHP数组,但代码必须用PHP编写。以下是JSON中的示例:
{
"extreme": {
"name": "item 1",
"chance": 1.0
},
"rare": {
"name": "item 2",
"chance": 9.0
},
"ordinary": {
"name": "item 3",
"chance": 90.0
}
}
对于上面的示例,以下情况属实:
item 1
(extreme
)应该从100次中选出1次item 2
(rare
)应该从100次中选出9次item 3
(ordinary
)应该从100次中选出90次简单来说:从数组或JSON字符串中随机挑选项目的代码,设置每个项目的百分比机会。
答案 0 :(得分:2)
但是我会把我留在这里备案:
<?php
$json_string = '
{ "extreme":{
"name":"item 1",
"chance":1.0
},
"rare":{
"name":"item 2",
"chance":9.0
},
"ordinary":{
"name":"item 3",
"chance":90.0
}
}';
$data = json_decode($json_string, true);
$arr = array();
// Cycle through "extreme", "rare" and "ordinary"
foreach($data as $item){
for($i=0; $i<$item['chance']; $i++){
// Add the item's name to the array, [chance] times
array_push($arr, $item['name']);
}
}
shuffle($arr); // shuffle the array
$chosen_item = $arr[array_rand($arr)]; // Result
echo $chosen_item;
?>
我做了一个测试循环,执行了50,000次,得到了这些结果:
'item 1' => chosen 223 times (00.4%)
'item 2' => chosen 5133 times (10.2%)
'item 3' => chosen 44644 times (89.2%)
答案 1 :(得分:2)
另一种方法:
$options = [
"extreme" => [
"name" => "item 1",
"chance" => 1.0,
],
"rare" => [
"name" => "item 2",
"chance" => 9.0,
],
"ordinary" => [
"name" => "item 3",
"chance" => 90.0,
]
];
$rand = rand(0, 99);
$max = 0;
foreach ($options as $option) {
$max += $option['chance'];
if ($rand < $max) {
break;
}
}
echo $option['name'], PHP_EOL;