PHP权重计算核心逻辑与代码实现
本示例详细解析了PHP中实现简易权重计算的方案,供开发者参考借鉴。具体实现细节如下:
//简单权重计算器
$data222=array(
0=>array('id'=>1,'name'=>'一等奖','weight'=>'3'),
1=>array('id'=>2,'name'=>'二等奖','weight'=>'1'),
2=>array('id'=>3,'name'=>'三等奖','weight'=>'5'),
3=>array('id'=>3,'name'=>'三等奖','weight'=>'1'),
);
// 权重数值越高,被返回的概率越大
// 原理生成权重个数的数组字,入array(5个0,10个1,25个2)
function countWeight($data){
$i=0;
$temp=array();
foreach($data as $v){
for($i=0;$i<$v['weight'];$i++){
$temp[]=$v;//放大数组
}
}
$num = count($temp); //查看网上的有错误,本人已改正
$int=mt_rand(0,$num-1);//获取一个随机数
$result=$temp[$int];
return $result; //返回一维数组
}
echo '';
var_dump(countWeight($data222));
代码运行后的实际输出结果表现为:
array(3) { ["id"]=> int(2) ["name"]=> string(9) "二等奖" ["weight"]=> string(2) "10" }
此外,为方便大家使用,这里额外推荐两款功能相近的实用在线工具:
在线随机数字/字符串生成工具: 点击使用
在线随机字符/随机密码生成工具: 点击使用
期望上述内容能对各位在PHP编程开发中有所帮助。