shuffle

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

shuffle

Post 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
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post 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];
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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().
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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
)
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

thanks feyd
Post Reply