问题
To shuffle an array in php is easy but my problem is when i try to shuffle it without getting the same result before of after that key.
Example:
Array ( 0 => 1, 1 => 2, 2 => 3, 3 => 3 )
I must have a result without 3 coming together.
Example of some array i want:
Array ( 0 => 2, 1 => 3, 2 => 1, 3 => 3 )
I've tryed to check each item of the array, if that happens i shuffle it again, and check another time. But that seems to be waste both on time and process.
EDIT: Here is the code i use:
do
{
$not_valid=false;
for($i=0;$i<sizeof($arr_times)-1;$i++){
if($arr_times[$i]==$arr_times[$i+1])
$not_valid=true;
}
if($not_valid)
shuffle($arr_times);
}while ($not_valid);
回答1:
Even though php has really a lot of strange functions - it doesn't have any for described situation.
So you have to do that manually.
PS: also it would be a good idea to check if it's even possible to shuffle input array in an expected way so you wouldn't get into an infinite loop.
回答2:
From Shuffle list, ensuring that no item remains in same position
<?php
$foo = array(
0,
1,
2,
3,
4,
);
for ($i = 0, $c = sizeof($foo); $i < $c - 1; $i++) {
$new_i = rand($i + 1, $c - 1);
list($foo[$i], $foo[$new_i]) = array($foo[$new_i], $foo[$i]);
}
var_export($foo); // Derangement
来源:https://stackoverflow.com/questions/12240388/shuffling-php-array-without-same-value-before-or-after