Jump to content

rand order array values


EchoFool

Recommended Posts

I have problems with my array

 

I build the array then i want to randomise the values.... not the positions... and that grab position[0] of what ever the value is of [0]

 

I tried this:

 

<?php
// $a is constructed for array

$a = array();
While($row = mysql_fetch_assoc($Find)){
If ($Level < $row['GreaterThan']){
}ElseIf ($DonatorDaysLeft < 1 && $row['Donator'] == 1){
}Else{
    $a[] = $row['RecordID'];
}

print_r($a);
$NewArray = array_rand($a);
Echo '<BR><BR>';
print_r($NewArray);
?>

 

 

Result:

Array ( [0] => 6 )

0Array ( [0] => 6 [1] => 8 )

1

 

Now firstly im confused why there is a 0 and 1 randomly inbetween each array and why the second array suddenly collected an extra value :S Its not making sense can any one explain my mistake?

Link to comment
Share on other sites

The [0] & [1] are positions. You're using an associative array. All arrays, whether you realize it or not, must have a key. If you don't assign a key, PHP will autmatically assign them sequentially.

 

I'm a little confused as to what you've wrote, so I'm just going to show how to randomize a query past the actual SQL (which should be used to the randomization actually, not this way):

 

$results = array();
$query = mysql_query($sql, $connection) or die( 'Error: ' . mysql_error() );
while ( $row = mysql_fetch_array( $query, MYSQL_ASSOC ) )
array_push( $results, $row );

shuffle($results);

print_r($results); // You'll see them in a randomized order now...

 

Since your if/else statements make no sense whatsoever, I didn't put them in the example above.

 

Basically, run a nice, clean, query. Then shuffle() your results (essentially does just that, randomizes the arrays' order).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.