Jump to content
Larry Ullman's Book Forums

paterdr

Members
  • Posts

    1
  • Joined

  • Last visited

paterdr's Achievements

Newbie

Newbie (1/14)

0

Reputation

  1. Hassan, Maybe this helps... I tried the following code and also accidentally discovered this effect of the shuffle() function mentioned in the tips on p. 68., shuffle($movies); echo '<tr><td colspan="2"><b>Random order by array_rand():</b></td></tr>'; foreach ($movies as $title => $rating) { echo "<tr><td>$rating</td> <td>$title</td></tr>\n"; } So I wanted to find a way to randomly sort that preserves the keys of the original array and thus acts in a similar fashion as the functions ksort() and arsort() used in the sample script (2.8). There are number of custom and clever solutions to be found online, which it may be improper to copy here. Is there a solution to shuffle() built into PHP itself? Perhaps uksort(). This function, however, requires a custom comparison function as a second parameter. To that end, here is a simple randomzier function: function drp_randomize() {return rand() > rand();} This can be used with uksort() as in the following line (note the quotes): uksort($movies, "drp_randomize"); This seems to work, as pressing F5 (refresh) in Firefox repeatedly re-sorts the array. I also found out that, if the shuffle() routine is left in the code, no subsequent solution will work as expected (i.e. with the orginal keys), as they have been permanently replaced by new keys/index numbers in the array, To work with the original array, with the keys intact, place the key-preserving workarounds before any shuffle() routine used on that array.
×
×
  • Create New...