shuffle not shuffling...

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
mjmacarty
Forum Commoner
Posts: 37
Joined: Tue Feb 21, 2006 3:20 pm

shuffle not shuffling...

Post by mjmacarty »

...coder does not know how to make it.

Code: Select all

$result = mysql_query($query, $conn) or die(mysql_error());

for ( $i=0; $i<3; $i++){
$row = mysql_fetch_array($result);

shuffle(array_keys($row));
This aways returns the same three products. Obviously I am missing the finer points of the old shuffle function.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

shuffle() manipulates the array given to it. Since you are not assigning the results of array_keys() to a variable, therefore the array is never actually changed.
mjmacarty
Forum Commoner
Posts: 37
Joined: Tue Feb 21, 2006 3:20 pm

Post by mjmacarty »

You mean like this?

Code: Select all

$result = mysql_query($query, $conn) or die(mysql_error());

for ( $i=0; $i<3; $i++){
$row = mysql_fetch_array($result);
$do_the_hustle = array_keys($row);
shuffle($do_the_hustle);
Is that different from the original code?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$do_the_hustle will be the shuffled array, so yes.
mjmacarty
Forum Commoner
Posts: 37
Joined: Tue Feb 21, 2006 3:20 pm

Post by mjmacarty »

OK. I think I see what's happening. I get random key values from the array. What I want is random "rows" from the array, as in random results from a query.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

you could get random results using the query instead of having php randomize your results..

ie..

Code: Select all

... ORDER BY RAND() LIMIT 4
mjmacarty
Forum Commoner
Posts: 37
Joined: Tue Feb 21, 2006 3:20 pm

Post by mjmacarty »

This seems easier to me (although I wouldn't mind knowing how to do this with php):

Code: Select all

$query = "SELECT * FROM books ORDER BY rand() LIMIT 3;";

$result = mysql_query($query, $conn) or die(mysql_error());

for ( $i=0; $i<3; $i++){
$row = mysql_fetch_array($result);
This is the effect I was looking for. Thanks for helping me sort through this.
mjmacarty
Forum Commoner
Posts: 37
Joined: Tue Feb 21, 2006 3:20 pm

Post by mjmacarty »

Jcart wrote:you could get random results using the query instead of having php randomize your results..

ie..

Code: Select all

... ORDER BY RAND() LIMIT 4

Heh, thanks. I thought of it in the shower!
Post Reply