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>'; 
LazyOne
  • 158,824
  • 45
  • 388
  • 391
HomeBrew
  • 849
  • 2
  • 12
  • 25

2 Answers2

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.

Ribose
  • 2,223
  • 16
  • 22
-1

Use shuffle to randomize :

foreach (shuffle($array) as $commentortweet) {
....
demental
  • 1,444
  • 13
  • 25