一段有意思代碼

<?php
class Red extends CI_Controller{
    public function rand()
    {
        $money = (float)$this->input->get('money');
        $num = (int)$this->input->get('num');
        $ret = [];
        $p_money = 0;
        for ($i = $num; $i > 0; $i--) {
            $p = $this->rand_money($money - $p_money, $i);
            $ret[] = $p;
            $p_money += $p;
        }
        $ret_arr = [];
        for ($i= 0;$i<$num;$i++){
            $p = array_rand($ret);
            $ret_arr[] = $ret[$p];
            unset($ret[$p]);
        }
        $this->success_message(['money'=>$ret_arr]);
    }

    public function rand_money($money, $num)
    {
        if ($money == 0) return 0;
        if ($num == 1) return round($money, 2);
        if ($money <= $num * 0.01) {
            return 0.01;
        }
        $money *= 100;
        return round(rand(1, $money - ($num - 1)) / 100, 2);
    }
}

這是基於ci的代碼php

結果:json

{
  "status": 1,
  "msg": "success",
  "data": {
    "money": [
      0.06,
      0.19,
      0.03,
      0.68,
      0.04
    ]
  }
}
相關文章
相關標籤/搜索