正如标题所说......让我们看看代码(更好地解释):
$maxItemAmount = 10;
$maxItemQtyTotal = 40;
$qtyMap = array_map(function () use ($maxItemQtyTotal) {
// returns something with rand()
// but relative to $maxItemQtyTotal
}, array_fill(0, $maxItemAmount, null));
// expecting: (10 items with a total qty of 40)
// [
// // numeric key => qty
// 0 => 3, // 3 total
// 1 => 4, // 7 total
// 2 => 9, // 16 total
// 3 => 2, // 18 ...
// 4 => 6, // 24
// 5 => 1, // 25
// 6 => 2, // 27
// 7 => 8, // 35
// 8 => 3, // 38
// 9 => 2, // 40
// ]
所以我发现了这个很好的“技巧”来在数组中创建偏移量,它允许我使用回调返回值。
我现在搜索的是一种返回随机数的方法,但相对于给定的输入$maxItemQtyTotal。
另一个例子:
$maxItemAmount = 4;
$maxItemQtyTotal = 81;
// expecting: (4 items with a total qty of 81)
// [
// // numeric key => qty
// 0 => 11, // 11 total
// 1 => 5, // 16 total
// 2 => 42, // 58 total
// 3 => 23, // 81 total
// ]
我不能回来rand(1, $maxItemQtyTotal)。我还得回去rand(1, $n)那里$n是最大数量的最大项目分
但仍然是随机的,从最后一个rand(1, $n)添加到下一个还剩下什么?
我希望我能描述一下:)
慕森王