Page 1 of 1
shuffle
Posted: Tue Aug 09, 2005 4:20 pm
by shiznatix
i need a function that is like shuffle but keeps the original keys so
Code: Select all
1 - one
2 - two
3 - three
4 - four
//turns into
3 - three
1 - one
4 - four
2 - two
Posted: Tue Aug 09, 2005 4:22 pm
by nielsene
uksort, using a random return for cmp_function
[edit: hmm now that I think about it, it might generate an infinite loop, depending on the sort innards....]
Perhaps a two pass algorithm:
Code: Select all
$keys =array_keys($arr);
shuffle($keys);
$newArr=array();
foreach($keys as $aKey) $newArr[$aKey]=$arr[$aKey];
Posted: Tue Aug 09, 2005 4:27 pm
by shiznatix
i did
Code: Select all
uksort($arrlines, rand(0, count($arrlines)));
but thats not giving me a random thing, it is always coming out with the same order, even if i just do rand().
Posted: Tue Aug 09, 2005 4:30 pm
by nielsene
shiznatix wrote:i did
Code: Select all
uksort($arrlines, rand(0, count($arrlines)));
but thats not giving me a random thing, it is always coming out with the same order, even if i just do rand().
You would need to pass in a function, not the result of the function. And the function would have to return -1 or 1, not a number between 0 and N
Posted: Tue Aug 09, 2005 4:36 pm
by feyd
Code: Select all
<?php
function ashuffle(&$array)
{
$keys = array_keys($array);
shuffle($keys);
$ret = array();
foreach($keys as $key)
{
$ret[$key] = $array[$key];
}
$array = $ret;
}
$test = array('a'=>'1234','b'=>'ASDF','c'=>'asdf','d'=>'qwer');
print_r($test);
ashuffle($test);
print_r($test);
$test = array('1234','ASDF','asdf','qwer');
print_r($test);
ashuffle($test);
print_r($test);
?>
output
Code: Select all
Array
(
[a] => 1234
[b] => ASDF
[c] => asdf
[d] => qwer
)
Array
(
[c] => asdf
[d] => qwer
[b] => ASDF
[a] => 1234
)
Array
(
[0] => 1234
[1] => ASDF
[2] => asdf
[3] => qwer
)
Array
(
[1] => ASDF
[2] => asdf
[0] => 1234
[3] => qwer
)
Posted: Wed Aug 10, 2005 2:41 am
by shiznatix
thanks feyd