选择多个&具有限制的随机值

时间:2018-01-22 02:25:24

标签: php arrays for-loop random implode

我这里有这个代码:

$ids = implode(',', array_rand(array_column($test, 'id', 'id'), 5));

以上代码的作用如下:

“首先通过id提取id列索引,然后选择5个随机的索引,最后内嵌到逗号分隔列表中。由于密钥必须是唯一的,这有额外的好处,即如果碰巧发生了不重复的id在数组中重复“这是来自我的previous question

现在,如果我将$arr从我的旧问题更改为:

Array
(
    [id] => 13
    [pets] => 8
    [num_of_times] => 3
)
Array
(
    [id] => 15
    [pets] => 8
    [num_of_times] => 6
)
Array
(
    [id] => 16
    [pets] => 10
    [num_of_times] => 2
)
Array
(
    [id] => 17
    [pets] => 9
    [num_of_times] => 4
)
Array
(
    [id] => 18
    [pets] => 10
    [num_of_times] => 3
)
Array
(
    [id] => 19
    [pets] => 10
    [num_of_times] => 10
)
Array
(
    [id] => 20
    [pets] => 0
    [num_of_times] => 11
)
Array
(
    [id] => 21
    [pets] => 8
    [num_of_times] => 9
)
Array
(
    [id] => 22
    [pets] => 9
    [num_of_times] => 0
)
Array
(
    [id] => 23
    [pets] => 4
    [num_of_times] => 3
)
Array
(
    [id] => 24
    [pets] => 0
    [num_of_times] => 1
)
Array
(
    [id] => 40
    [pets] => 8
    [num_of_times] => 0
)
Array
(
    [id] => 43
    [pets] => 2
    [num_of_times] => 2
)

num_of_times是可以选择id或“用户”的次数。

所以,如果我有for loop这样的话:

for ($i = 1; $i <= 10; $i++) {
    $ids = implode(',', array_rand(array_column($arr, 'id', 'id'), 5));
    echo $ids;
}

我怎样才能确保,例如,id 13 的第一个数组 NOT 进入$ids超过3次但CAN进入{在$ids时,{1}} 3次或更少? (这适用于所有id)

例如,最终结果将是这样的:

for loop

2 个答案:

答案 0 :(得分:2)

这是解决此问题的一种方法

$num = array_column($test, 'num_of_times', 'id'); // get each num_of_times with id as index
for ($ids = '', $i = 1; $i <= 10; $i++) {         // Your for loop
    $num = array_filter($num);                    // Filter $num array
    $rand = array_rand($num, 5);                  // get 5 random element
    $ids .= implode(',', $rand) . '<br>';         // implode then concatenate to $ids var
    foreach ($rand as $id) {                      // Run a foreach loop to $rand array
        $num[$id]--;                              // Decrement num_of_times
    }
}
echo $ids;  // Echo result

答案 1 :(得分:1)

嗨,请尝试我的代码,如果它符合您的需求。如果要限制每个数据的使用,只需添加更多数组数据。

<script type="text/javascript">  

  function VallidRcvQuantity() {
      var gridViewCtlId = '<%=gvGoodReceived.ClientID%>';
      var grid = document.getElementById(gridViewCtlId);
      var txtcurrentrcvamount = document.getElementById(txtrcvQuantity).value;
      var cell = grid.rows[0].cells[2].textcontent;
      if (txtcurrentrcvamount > cell ) {
          alert("Receive quantity must be less or equal PO quantity");
          return false;
      }
      return true;  
  }