note 41047 added to function.shuffle
| From: | chvickers at hotmail dot com | Date: | Sun, 28 Mar 2004 18:02:52 +0000 |
| Subject: | note 41047 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-67286@lists.php.net to get a copy of this message | ||
we all know the shuffle() is bad for shuffeling normal arrays and even worse for shuffeling
associate multi arrays
to avoid loosing your associative keys in an associative multidimensional array use this shuffle
function: (it is not perfect but it works)
function mix($org_arr) {
$keys = array_keys($org_arr);
$max = count($org_arr)-1;
for ($y = 1; $y <= pow($max+1,3); $y++) {
mt_srand((double)microtime()*1000000);
$r = mt_rand(0,$max);
$new_arr[$keys[$r]] = $org_arr[$keys[$r]];
}
return $new_arr;
}
function swapshuffle($array) {
srand ((double) microtime() * 10000000);
for ($i=0;$i<sizeof($array);$i++) {
$from=rand(0,sizeof($array)-1);
$old=$array[$i];
$array[$i]=$array[$from];
$array[$from]=$old;
}
return $array;
}
function submix($org_arr) {
$keys = array_keys($org_arr);
$max = count($org_arr)-1;
for ($y = 0; $y <= $max; $y++) {
$new_arr[$keys[$y]] = swapshuffle($org_arr[$keys[$y]]);
}
return $new_arr;
}
$boxes = submix($boxes); # shuffles the subarrays
$boxes = mix($boxes); # shuffles the main array
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41047
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41047&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41047&report=yes
Search -- http://master.php.net/manage/user-notes.php