php中的随机洗牌?
我正在创建一个彩票来将人们配对。所以我想要一种方法来随机排列数组中的字符串,其中没有项目最终出现在同一位置。 (你无法与自己配对)
public function shuffleSantas(){
$query = $this->db->get('person');
$givers = array();
$recievers = array();
foreach($query->result() as $row):
$givers[] = $row->name;
//here i want a random order, but no name can be on the same place as in $givers!
$recievers[] = '';
endforeach;
I'm creating a lottery to pair up people. So I want a way to shuffle the strings in an array where no item ends up on the same place. (You can't pair up with yourself)
public function shuffleSantas(){
$query = $this->db->get('person');
$givers = array();
$recievers = array();
foreach($query->result() as $row):
$givers[] = $row->name;
//here i want a random order, but no name can be on the same place as in $givers!
$recievers[] = '';
endforeach;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将数组打乱一次,然后将第一个元素与第二个元素配对,第二个元素与第三个元素配对,等等,最后一个元素与第一个元素配对。
shuffle the array once and then pair up the first element with the second, the second with the third etc. and the last with the first.
在这种情况下,一个人将能够从一个人那里获得并给予另一个人。可以吗?而且这个算法也不是最优的,如果数组中只有一个人,肯定会陷入无限循环。
In this case one will be able to receive from one person and to give to other person. Is it OK? Also, this algorithm is not optimal and will definitely fall into infinity loop if there is only one person in an array.
如果认为 PHP 中没有内置函数可以以这种方式进行洗牌。您必须编写自己的函数。
If think there is no built-in function in PHP to shuffle that way. You have to write your own function.