码迷,mamicode.com
首页 > Web开发 > 详细

php红包

时间:2016-04-29 22:16:22      阅读:358      评论:0      收藏:0      [点我收藏+]

标签:

/**   转http://www.oschina.net/code/snippet_1392428_54532     谢谢 php_fangting
* @param $total [你要发的红包总额]
* @param int $num [发几个]
* @return array[生成红包金额]
*/
function getRedGift($total, $num = 10)
{
$min = 0.01;
$wamp = array();
$returnData = array();
for ($i = 1; $i < $num; ++$i) {
$safe_total = ($total - ($num - $i) * $min) / ($num - $i); //红包金额的最大值
if ($safe_total < 0) break;
$money = @mt_rand($min * 100, $safe_total * 100) / 100;//随机产生一个红包金额
$total = $total - $money;//剩余红包总额
$wamp[$i] = round($money, 2);//保留两位有效数字
}
$wamp[$i] = round($total, 2);
$returnData[‘MoneySum‘] = $wamp;
$returnData[‘newTotal‘] = array_sum($wamp);
return $returnData;
}
//测试
$data = getRedGift(100, 10);
print_r($data);
//result:
/*
Array
(
[1] => 8.7
[2] => 10.09
[3] => 6.23
[4] => 6.87
[5] => 0.47
[6] => 3.12
[7] => 7.52
[8] => 12.21
[9] => 20.53
[10] => 24.26
)*/

 

 

 

public function rands($total=0, $num=3, $bonus_type=1)

{

$m = $total;

// $total=10;//红包总额

//$num=8;// 分成8个红包,支持8人随机领取

$min=0.01;//每个人最少能收到0.01元

$res = array();

for ($i=1;$i<$num;$i++)

{

$safe_total = ($total-($num-$i)*$min)/($num-$i);//随机安全上限

$money = mt_rand($min*100,$safe_total*100)/100;

$total = bcsub($total, $money, 2);

 

$res[] = $money; 

        }

        $res[]=  $m - array_sum($res);

        return $res;

}

 

 

public function hongbaoAction()

{  

 

// 发3个拼手气红包,总金额是100元

for ($i = 0 ;$i< 10000; $i++)

{

$bonus_items  = $this->rands(100, rand(3, 60), 1);

// 查看生成的红包

$arr = array();

$arr[‘typeid‘] = $bonus_items[0];

$arr[‘nums‘]= $bonus_items[1];

$arr[‘change_nums‘] = $bonus_items[2];

$arr[‘dateline‘] = array_sum($bonus_items);// 校验总金额是不是正确,看看微信有没有坑我们的钱 

$this->mainModel->test($arr);

unset($arr, $bonus_items);

}

 

 

}

 

php红包

标签:

原文地址:http://www.cnblogs.com/sixiong/p/5447574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!