PHP 如何在块之后重新创建数组的随机顺序

问题描述 投票:0回答:1

对于在线游戏,我创建了一个包含 36 个值的初始 PHP 数组:A-Z 0-9。随机脚本重新混合数组,即

[0] R
[1] 4
[2] N
[3] d
...
[35] 8

完成后,脚本会通过

chunk($arr,6)
为 6 名玩家每人分配 6 个标志。

Player 1 [0] = [R,4,n,d,O,M]
Player 2 [1] = [p,2,s,Z,k,u]
...
Player 6 [5] = [J,r,V,5,z,8]

问题是:一旦球员名单按字母顺序重新排序,是否有一种算法方法可以重新创建初始分布?

简化问题:

初始数组

[0] = abc
[1] = def
[2] = ghi
[3] = jkl
[4] = mno
[5] = pqr

随机顺序排列 [0,1,2,3,4,5] -> [2,5,0,3,1,4]:

[2] = ghi
[5] = pqr
[0] = abc
[3] = jkl
[1] = def
[4] = mno

结果:

new order     [0]   [1]   [2]   [3]   [4]   [5] 
value         ghi   pqr   abc   jkl   def   mno
former order  [2]   [5]   [0]   [3]   [1]   [4] -> random permutation

要检索以前的订单,我必须找到生成数组 [2,4,0,3,5,1] 的方法:

 new order   [2]   [4]   [0]   [3]   [5]   [1]          
 value       abc   def   ghi   jkl   mno   pqr  -> initial array order

如何从随机排列[2,5,0,3,1,4]中得到这个数组[2,4,0,3,5,1]?

php arrays permutation
1个回答
0
投票

是的,有一种方法可以做到这一点。假设您有一个名为

$array
的数组,并且您将其放入
function
中(非常重要!),您通过值而不是地址传递数组。示例:

?php

$array = ['a','b','c','d','e','f'];

function shuffleMyArray($array) {
    shuffle($array);
    return $array;
}

$shuffled = shuffleMyArray($array);

echo json_encode([
    'original' => $array,
    'shuffled' => $shuffled
]);

输出示例:

{"original":["a","b","c","d","e","f"],"shuffled":["a","d","c","f","b","e"]}
© www.soinside.com 2019 - 2024. All rights reserved.