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
https://forums.phpfreaks.com/topic/155439-rand-order-array-values/
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).

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.