0

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?

2

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm. Thanks. Also, I have another array of "transactions" if you will, and it's descending from oldest to newest when I want it newest to oldest, how can I flip it via timestamp? $Transactions = $RPC2->listtransactions($_SESSION['email']); foreach($Transactions as $Transaction) { echo '<tr>'; echo '<td>' . date("F j, g:i A", $Transaction['timereceived']) . '</td>'; echo '<td>' . $Transaction['address'] . '</td>'; echo '<td>' . $Transaction['amount'] . '</td>'; }
I did a sort() around the $Transactions var and it didn't change anything.
How can I order them by which timestamp is greatest?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.