php微信紅包演算法
阿新 • • 發佈:2018-12-31
/**生成紅包的函式*/ function getRandMoney($totalMoney, $totalPeople=2, $miniMoney=1){ $randRemainMoney = $totalMoney - $totalPeople * $miniMoney;//剩餘需要隨機的錢數 return _getRandMoney($randRemainMoney, $totalPeople, $miniMoney); } /**紅包生成的邏輯程式碼*/ function _getRandMoney($totalMoney, $totalPeople, $miniMoney){ $returnMessage = array('status'=>1, 'data'=>NULL); if($totalMoney > 0){ $returnMessage['data'] = _randMoney($totalMoney, $totalPeople, $miniMoney); }elseif($totalMoney == 0){ $returnMessage['data'] = array_fill(0, $totalPeople, 1); }else{ $returnMessage['status'] = -1; $returnMessage['data'] = '引數傳遞有誤,生成紅包失敗'; } return $returnMessage; } /*引數無誤,開始生成對應的紅包金額*/ function _randMoney($totalMoney, $totalPeople, $miniMoney){ $data = array_fill(0, $totalPeople, $miniMoney); if($totalPeople > 1){ foreach($data as $k => $v){ if($k == $totalPeople -1){ $data[$k] = $totalMoney + $v; break; }else { if($totalMoney == 0) break; $randMoney = rand(0, $totalMoney); $totalMoney -= $randMoney; $data[$k] = $randMoney + $v; } } } return $data; }