从数组中选择 n 个随机值
我有一个对象数组,我需要随机选择其中 8 个。我最初的想法是使用 array_rand(array_flip($my_array), 8) 但这不起作用,因为对象不能充当数组的键。
我知道我可以使用 shuffle
,但我担心随着数组大小的增加,性能会受到影响。这是最好的方法,还是有更有效的方法?
I have an array of objects and I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8)
but that doesn't work, because the objects can't act as keys for an array.
I know I could use shuffle
, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
请注意,
shuffle()
函数提供参数作为引用并对其进行更改。Notice that
shuffle()
function gives parameter as a reference and makes the changes on it.您可以使用 array_rand 随机选择键,并使用 foreach 收集对象:
You could use
array_rand
to pick the keys randomly and aforeach
to gather the objects:我刚刚在我们的代码中发现了这一点,并希望找到一个更具可读性的解决方案:
I just found this in our code and was hoping to find a more readable solution:
有多种方法可以完成此任务,但不同的方法会提供微妙的结果。如果值是对象或任何其他数据类型,则没有区别。我的演示将使用从 1 到 9 的数字范围。
“shuffle & slice”
shuffle()
通过引用进行修改。代码:(Demo)
或
“array_rand (w/ count) & iterate”
经典 foreach:(演示)
函数式单行:(Demo)
"array_rand (w/ count) & Flip & intersect_key"
代码:(演示)
“array_rand的循环调用”
range()
并不是超级优雅。经典 foreach:(演示)
函数式 (演示)
There are several ways to accomplish this task, but different approaches offer nuanced results. It makes no difference if the values are objects or any other data type. My demos will use a range of numbers from 1 to 9.
"shuffle & slice"
shuffle()
modifies by reference.Code: (Demo)
or
"array_rand (w/ count) & iterate"
Classic foreach: (Demo)
Functional-style one-liner: (Demo)
"array_rand (w/ count) & flip & intersect_key"
Code: (Demo)
"looped calls of array_rand"
range()
is not super elegant.Classic foreach: (Demo)
Functional-style (Demo)
又怎么样?:
What about?:
您可以使用此函数从数组中获取多个随机元素:
You can get multiple random elements from an array with this function:
您可以尝试使用此
函数
来重新混合您的对象
:此函数获取您的对象并重新混合它,然后在直接编辑时以新顺序返回它
You may try using this
function
to remix yourobject
:this function takes your object and remixes it then returns it in a new order as it gets directly edited