Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Random Shuffle Array Maintaining Key => Value

Tags:

arrays

php

I've been looking on google for the answer but can't seem to find something fool-proof and cant really afford to mess this up (going live into a production site).

What I have is an advanced search with 20+ filters, which returns an array including an ID and a Distance. What I need to do is shuffle these results to display in a random order every time. The array I have that comes out at the moment is:

Array (
    [0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
    [1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
    [2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
    [3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
    [4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
)

What I need to be able to do is randomise or order of these every time but maintain the id and distance pairs, i.e.:

Array (
    [4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
    [1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
    [3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
    [2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
    [0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
)

Thanks :)

like image 752
lethalMango Avatar asked Nov 05 '10 01:11

lethalMango


People also ask

How do I randomize an array in PHP?

The shuffle() Function is a builtin function in PHP and is used to shuffle or randomize the order of the elements in an array. This function assigns new keys for the elements in the array. It will also remove any existing keys, rather than just reordering the keys and assigns numeric keys starting from zero.

How do you optimally shuffle an array?

A simple solution is to create an auxiliary array temp[] which is initially a copy of arr[]. Randomly select an element from temp[], copy the randomly selected element to arr[0], and remove the selected element from temp[]. Repeat the same process n times and keep copying elements to arr[1], arr[2], … .

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How does PHP shuffle work?

shuffle() function is based on the same generator as rand() , which is the system generator based on linear congruential algorithm. This is a fast generator, but with more or less randomness. Since PHP 4.2. 0, the random generator is seeded automatically, but you can use srand() function to seed it if you want.


3 Answers

The first user post under the shuffle documentation:

Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

function shuffle_assoc($list) { 
  if (!is_array($list)) return $list; 

  $keys = array_keys($list); 
  shuffle($keys); 
  $random = array(); 
  foreach ($keys as $key) { 
    $random[$key] = $list[$key]; 
  }
  return $random; 
} 

Test case:

$arr = array();
$arr[] = array('id' => 5, 'foo' => 'hello');
$arr[] = array('id' => 7, 'foo' => 'byebye');
$arr[] = array('id' => 9, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
like image 152
karim79 Avatar answered Oct 13 '22 20:10

karim79


As of 5.3.0 you could do:

uksort($array, function() { return rand() > rand(); });
like image 29
Hamish Avatar answered Oct 13 '22 20:10

Hamish


Take a look to this function here :

     $foo = array('A','B','C'); 


function shuffle_with_keys(&$array) {
    /* Auxiliary array to hold the new order */
    $aux = array();
    /* We work with an array of the keys */
    $keys = array_keys($array);
    /* We shuffle the keys */`enter code here`
    shuffle($keys);
    /* We iterate thru' the new order of the keys */
    foreach($keys as $key) {
      /* We insert the key, value pair in its new order */
      $aux[$key] = $array[$key];
      /* We remove the element from the old array to save memory */
      unset($array[$key]);
    }
    /* The auxiliary array with the new order overwrites the old variable */
    $array = $aux;
  }

      shuffle_with_keys($foo);
      var_dump($foo);

Original post here : http://us3.php.net/manual/en/function.shuffle.php#83007

like image 45
v1r00z Avatar answered Oct 13 '22 18:10

v1r00z