【发布时间】:2018-01-22 02:25:23
【问题描述】:
我这里有这段代码:
$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 次,但可以进入 $ids 3 次或更少,在for loop? (这适用于所有 id)
例如,最终结果会是这样的:
13,15,17,19,23
13,21,22,40,43
13,15,17,19,23
15,23,24,40,43 // 13 cannot be selected anymore because it already hit the "num_of_times" limit which is 3 for the number 13. Same thing for all the other numbers/id's
...
...
...
...
...
...
【问题讨论】:
-
如果你想使用你当前的代码,这将成为非常任意的代码。最好的用途是编写递归函数并放弃您当前的代码。如果您从数组中生成 5 个唯一 ID,然后检查是否由于 num_of_times 而所有 5 个都可以使用,则必须生成 5 个适合的 ID,如果其中一个不能再使用,则丢弃所有 ID。使用递归函数,您可以生成 1 个 id 并检查您是否仍然可以使用它。这样会更有效率。
-
一行相同的数字无效吗?例如。
13, 13, 15, 17, 19 -
@Motbrok 你能给我指出正确的方向吗?使用什么功能等等?
-
@Erwin 不能有重复的数字
-
如果只有 3 个 id 没有达到他们的
num_of_times,那行只有 3 位数吗?例如。19, 20, 21(因为他们有很高的 num_of_times) 或者是否有足够的数据来防止这种情况发生?
标签: php arrays for-loop random implode