Thursday, 30 August 2018

Mixing an array in a PHP foreach loop

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>';


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.

0 comments:

Post a Comment