I have this array
Array
(
[19] => Array
(
[nState] => -1
[bActive] => 1
)
[20] => Array
(
[nState] => -1
[bActive] => 1
)
[21] => Array
(
[nState] => -1
[bActive] =>
)
I want to make a random for this array but always get the same values. For example I want to get always the array with keys 12 11 13 10
. I searched on web but always the values are differents. Can you help me please ? Thx in advance and sorry for my english
You could use this variant of shuffle
:
function shuffled_seed($arr, $seed) {
$len = count($arr);
$shuffled = [];
while ($len) {
$shuffled[] = array_splice($arr, $seed % $len, 1)[0];
$seed = floor($seed / $len);
$len--;
}
return $shuffled;
}
If you provide twice the same arguments, you'll get twice the same return value. The second argument is the seed. You could for instance generate this as a random number the first time, but then remember it for any next time you need to reproduce the same array.
Example call:
$arr = [1,2,3,4,5,6,7,8,9];
$seed = rand();
$result = shuffled_seed($arr, $seed);
print_r($result);
$result = shuffled_seed($arr, $seed); // same seed
print_r($result); // same result