user2967388
user2967388

Reputation: 49

Choosing random data from an array (PHP)?

I wrote some code that works fine and uses a for statement to iterate over the array and display the eight results like I want it to.

$Address = $RPC2->getaddressesbyaccount($_SESSION['email']); 
$iteration_addresses = 0;

    foreach($Address as $Another) {
        $iteration_addresses++;
        echo '<b>' . $Another . '</b><br /><br />';
        if($iteration_addresses == 8) break;
    }

But it usually chooses the same 8 results, how can I have it choose random results each AJAX call?

Upvotes: 0

Views: 64

Answers (2)

sharif2008
sharif2008

Reputation: 2798

You can simply get exactly 8 randoms variables by your SQL QUERY like this:-

SELECT column FROM table
WHERE email='Your_email'
ORDER BY RAND()
LIMIT 8

I think this is CI framework then implement your model function like this

function getaddressesbyaccount($email)
{
   $this->db->order_by('address', 'RANDOM');
   $this->db->limit(8);
   $this->db->where(array('email'=>$email));
   $query = $this->db->get('table_name');
   return $query->result_array();
}

Then you can use this functions in your ajax implementations. Thanks.

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

Just shuffle() your array before you pick up entries.

This function shuffles (randomizes the order of the elements in) an array.

$Address = $RPC2->getaddressesbyaccount($_SESSION['email']); 
shuffle($Address); // Here
$iteration_addresses = 0;

    foreach($Address as $Another) {
        $iteration_addresses++;
        echo '<b>' . $Another . '</b><br /><br />';
        if($iteration_addresses == 8) break;
    }

Fiddle (taken from PHP.net)

Upvotes: 1

Related Questions