3

I'm trying to display an array in a random order in a foreach loop in PHP. I don't know whether to create a randomizing loop to do this or whether there is a randomizing function. I'm capturing information from the Facebook and twitter api's with the goal to mix the results and display as a list of comments from Facebook wall and tweets from twitter.

As you can see below, I first merge the two arrays from Facebook and twitter into one, and then loop through them in a foreach loop to display. currently all the Facebook one show first, and then twitter. I want to mix the two randomly. Sorry about the code, I hacked it together pretty quickly.

If you've got a totally different way to do this as well please don't hold back, I'm all ears! ;)

Here is what I have code wize:

$array = array_merge ($comments, $tweets);
foreach ($array as $commentortweet) 
{
    echo '<li>'. $commentortweet->picture. $commentortweet->message . $commentortweet->updatetime . 
        $commentortweet->content. $commentortweet->user . $commentortweet->author .'</li>';
}
echo '</ul>'; 
1
  • Sorry guys, the code has displayed a little squwed ;) it's still pretty legible though. Commented Jul 10, 2011 at 20:25

2 Answers 2

4

You can use your method of merging the two arrays then shuffle them using shuffle($array). You may then loop through the new order and print them out.

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

1 Comment

Ahaa... so simple - Thanks so much, quickest fix I ever got. Cheers!
-1

Use shuffle to randomize :

foreach (shuffle($array) as $commentortweet) {
....

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.